在JavaScript对象字面量中无法定义变量

9

为什么这段代码能够工作...

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

...但这个却没有效果?

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

我遇到了“both未定义”的错误。这里我错过了什么?this.both有问题吗?当涉及对象文字时,我是一个完全的新手。


TypeError: Cannot read property 'text1' of undefined - Matt Ball
这只是我一个人的问题还是两个例子都不应该工作? - aaronman
4个回答

6

因为在第二种情况下,在定义both时,this仍然不存在。如果您将both转换为方法,就像在这个例子中:http://jsfiddle.net/YyWMQ/,它会起作用。

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

在我看来,这是一个好问题,点赞!


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();

要理解它,您可以尝试以下操作。
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();

1
您的误解在以下行中:

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

您可以使用函数并返回一个值,例如:
both: function(){ return this.texts.text1 + ' ' + this.texts.text2 + '!'; } ,

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

1

当调用greet时,`this'将是父对象message。但实际构造message对象时并非如此。您可以编写类似以下的内容:

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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接