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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With