2013-06-21 27 views
8

为什么此代码的工作...在JavaScript中不能定义变量对象字面

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

它给我“两个都没有定义”的错误。我在这里错过了什么? this.both有什么不对吗?我是新手,当谈到对象文字

+0

'类型错误:的undefined' –

+0

无法读取属性“文本1”难道只是我还是应该两个例子不行 – aaronman

回答

6

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

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

恕我直言,很好的问题,+1

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 + '!', 

你可以用作乐趣ction和返回的值等:

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

最后

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

当调用打招呼,`这将是父OBJ,消息。当你实际构造消息对象时,情况并非如此。你可以写类似的喜欢的东西:

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