Вопрос

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