参见英文答案 > Self-references in object literals / initializers 21个
如何在这个简单的例子中简单地引用这个(obj)? (在这个确切的情况下,使用obj.文字)?
var obj = {
planet : "World!",// ok,let's use this planet!
text : {
hi: "Hello ",pl: this.planet // WRONG scope... :(
},logTitle : function(){
console.log( this.text.hi +''+ this.planet ); // here "this" works !
}
};
obj.logTitle(); // WORKS! // "Hello World!"
console.log( obj.text.hi +''+ obj.text.pl ); // NO DICE // "Hello undefined"
我也尝试过这样做:这个,但在内部对象中又未定义
最佳答案
不要使用object literal,使用函数方法,
var Obj = function(){
var self = this; //store self reference in a variable
self.planet = "World!",let's use this planet!
self.text = {
hi: "Hello ",pl: self.planet
};
self.logTitle = function(){
console.log( self.text.hi +''+ self.planet );
}
};
var obj = new Obj();
console.log( obj.text.hi +''+ obj.text.pl );
obj.logTitle();
这是工作jsfiddle:http://jsfiddle.net/cettox/RCPT5/.