如何访问像这样的子对象的父属性?
var foo = function foo(input){ this.input = input; };
function bar(input){ return new foo(input); }
foo.prototype = {
baz : {
qux : function(){
alert(this.parent.input );
}
},
corge : function(){
alert(this.input );
}
}
bar('test').corge(); //alerts 'test'
bar('test').baz.qux(); //errors 'this.parent is undefined'
答案 0 :(得分:1)
如何为这样的子对象访问
this.obj
?
你不能。
有一个baz
,无论有多少new foo
,因此无法从通常指向单身this
的{{1}}映射到特定foo.prototype.baz
foo
的实例。
看起来您可能打算为baz
的每个实例创建一个foo
。
试试这个
function foo(input) {
this.baz = {
parent: this,
qux: quxMethod
};
this.input = input;
}
foo.prototype.corge = function () { alert(this.input); };
function quxMethod() {
alert(this.parent.input);
}
答案 1 :(得分:0)
<击>
尝试定义baz
,如下所示:
baz : (function(){
var parent = this;
return {
qux : function(){
alert(parent.obj);
}
}
})()
击> <击> 撞击>
我相信这会做你想做的事:
演示:http://jsfiddle.net/maniator/rKcwP/
代码:
var foo = function foo(input) {
this.input = input;
};
function bar(input) {
return new foo(input);
}
foo.prototype = {
baz: function() {
var parent = this;
return {
qux: function() {
alert(parent.input);
}
}
},
corge: function() {
alert(this.input);
}
}
bar('test').corge(); //alerts 'test'
bar('test').baz().qux(); //alerts 'test'