Alex Rivera | Logout

How to reference properties of current object in JS

Asked 2012-12-25T22:36:27.210
14

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.

Edit
Report

1 Answer

4

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

answered 2012-12-25T22:45:52.583

Your Answer