13

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.

Community
  • 1
  • 1
Rayjax
  • 7,494
  • 11
  • 56
  • 82

2 Answers2

13

There is no way to reference the object, but you can add the properties dynamically:

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

object.wholename = object.firstname + object.lastname;

EDIT:

And why not wrap it in a function?

var makePerson = function (firstname, lastname) {
    return {
        firstname: firstname,
        lastname: lastname,
        wholename: firstname + lastname  // refers to the parameters
    };
};

var object = makePerson('john', 'paul');
Stefan
  • 4,166
  • 3
  • 33
  • 47
  • Ok thank you. The why I am doing this is that I am trying to have a well organized code in a huge web app I am building ; and so I decided to regroup similar functions and variables in objects like this. Is this the right way of doing it ? I know about TypeScript and Modules but do I need to use TS to achieve something as simple as groups of functions/variables ? – Rayjax Dec 25 '12 at 22:41
  • 2
    @user1397271 you can do this in plain JS: try introducing namespaces (like var MYAPP = { }; MYAPP.data = ...) and try breaking down big functions into smaller ones. Consider using the module pattern: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth – Stefan Dec 25 '12 at 22:45
  • when you say namespaces like var MYAPP = {}, it means it is the same as my example with var object = {}, so will I run into the problem I was asking about ? – Rayjax Dec 25 '12 at 22:47
  • @user1397271 yes, it will if you need to reference the thing that you're defining at the same time. But libraries can help with that, i.e. https://github.com/fabiooshiro/namespace-js or http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/ – Stefan Dec 25 '12 at 22:52
3

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

user1574041
  • 247
  • 4
  • 16