質問

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

役に立ちましたか?

解決

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

他のヒント

var message = {
    texts: {
        text1: 'Hello',
        text2: 'World'
    },
    // here this refers to the scope where message is defined 
    both: this.texts.text1 + ' ' + this.texts.text2 + '!', 
    greet: function() {
        console.log(this.both);
    }
}
message.greet();

To understand it you can try as given below

this.texts =  {
            text1: 'Alternate Hello',
            text2: 'World'
        };

var message = {
        texts: {
            text1: 'Hello',
            text2: 'World'
        },
        // here this refers to the scope where message is defined 
        both: this.texts.text1 + ' ' + this.texts.text2 + '!', 
        greet: function() {
            console.log(this.both);
        }
    }
message.greet();

Your misunderstanding is at the following line:

both: this.texts.text1 + ' ' + this.texts.text2 + '!',

You could use as function and return a value like:

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

And finally

 greet: function() {
        console.log(this.both());
    }

When calling greet, `this' will be the parent obj, message. This is not the case when you're actually constructing the message object. You could write something similar like:

var Message = function () {
    this.texts = {
        text1: 'Hello',
        text2: 'Word'
    }
    this.both = this.texts.text1 + ' ' + this.texts.text2 + '!';
}

Message.prototype.greet = function () {
    console.log(this.both);
}

message = new Message();
message.greet();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top