Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference properties of current object in JS [duplicate]

Possible Duplicate:
Self-references in object literal declarations

I have some simple objects in JS like this example:

var object = {
 firstname : 'john',
 lastname : 'paul',
 wholename : firstname + lastname
}

Well this simple thing doesn't work; john and paul are undefined in wholename, so I tried to use the 'this' operator which works ONLY if I do a function (getWholeName(){return this.firstname+this.lastname} ). But if I want to use a variable and not a function, how can I do? I also tried object.firstname + object.lastname but it doesn't work.

like image 236
Rayjax Avatar asked Dec 25 '12 22:12

Rayjax


People also ask

How do you copy properties from one object to another JS?

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

How is an object property referenced in JavaScript?

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true. For more information about comparison operators, see equality operators.

Does JavaScript copy object by reference?

Objects and ArraysObjects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory. Passed by reference.


1 Answers

In Javascript, every function is an object. You should declare your Object's constructor as a function like this:

function person(firstname,lastname)
{
this.firstname=firstname;
this.lastname=lastname;

this.wholeName=wholeName;

 //this will work but is not recommended.
 function wholeName()
 {
 return this.firstname+this.lastname;
 }
}

you can add extra methods to your object by prototyping it aswell , which is the recommended way of doing things. More info here:

http://www.javascriptkit.com/javatutors/proto.shtml

like image 110
user1574041 Avatar answered Oct 11 '22 19:10

user1574041