Search code examples
javascriptobject-literal

Can't define variable in JavaScript object literal


Why does this code work...

var message = {
    texts: {
        text1: 'Hello',
        text2: 'World'
    },
    greet: function() {
        console.log(this.texts.text1 + ' ' + this.texts.text2 + '!');
    }
}
message.greet();

...but this doesn't?

var message = {
    texts: {
        text1: 'Hello',
        text2: 'World'
    },
    both: this.texts.text1 + ' ' + this.texts.text2 + '!',
    greet: function() {
        console.log(this.both);
    }
}
message.greet();

It gives me "both is not defined" error. What am I missing here? Something's wrong withthis.both? I'm total newbie when it comes to object literal


Solution

  • Because in second case this is still not exist when you define both. if you will turn both to method, like in this example : http://jsfiddle.net/YyWMQ/ , it will work.

    both: function(){ return this.texts.text1 + ' ' + this.texts.text2 + '!'}  
    

    Imho , good question , +1