对象中对象中的Javascript`this`? [英] Javascript `this` in objects-in-objects?
问题描述
抱歉,帖子标题模糊,我无法为这篇帖子用英文写出正确的名称.
Sorry for fuzzy post title, I can't formulate the correct name in English for this post.
例如我有这样一个对象:
For example I have such an object:
var APP = {
a : 1,
b : function(){
return this.a;
}
}
这样,如果我调用 console.log ( APP.b() )
而 this
将引用 APP,结果将是 1代码>.
In such way, if I call console.log ( APP.b() )
than this
will be referring to APP and result will be 1
.
但是如何从子对象连接到APP呢?示例:
But how to connect to APP from sub-object? Example:
var APP = {
a : 1,
b : function(){
return this.a;
},
c : {
c1: function(){
return APP.a;
}
}
}
console.log ( APP.c.c1() ) // 1
此示例有效,但直接指向 APP 是个坏主意.例如:
This example works, but it's bad idea to point directly to APP. For example:
APP2 = APP;
APP = null;
console.log ( APP2.b() ); // 1
console.log ( APP2.c.c1() ); // APP is undefined
UPD:
我有一半的决定:如果我像方法一样声明属性 c
:
I've got half-decision:
if I declare property c
like a method:
c : function(){
var self = this;
return {
c1: function(){
return self.b();
},
c2: function(){}
}
}
它会工作,但我应该调用一个方法而不是属性(括号太多):
It will work, but I should call a method but not property (too much brackets) :
console.log( APP2.c().c1() )
而不是 console.log( APP2.c.c1() )
推荐答案
您可以创建工厂方法:
var APP = (function(){
var self;
return self = {
a : 1,
b : function(){
return this.a; // could be self, only differs in non-context use
},
c : {
c1: function(){
return self.a;
}
}
};
})();
APP2 = APP;
APP = null;
APP2.b(); // 1
APP2.c.c1(); // 1
这篇关于对象中对象中的Javascript`this`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!