[英]javascript OOP get from parent object
How can I access the parent attribute of a child object like this? 我该如何访问子对象的父属性?
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'
How can I access
this.obj
for a child object like this? 如何访问this.obj
的子对象?
You can't. 你不能
There is one baz
regardless of how many new foo
there are, so there is no way to map from this
which typically points to the singleton foo.prototype.baz
to a specific instance of foo
. 有一个baz
不管有多少new foo
也有,所以没有办法从地图this
通常指向单foo.prototype.baz
到的特定实例foo
。
It looks like you probably meant to create a baz
per instance of foo
. 看来您可能打算为foo
每个实例创建一个baz
。
Try this 尝试这个
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);
}
Try defining
baz
like so:
尝试像这样定义
baz
:
baz : (function(){ var parent = this; return { qux : function(){ alert(parent.obj); } } })()
I believe this will do what you want it to do: 我相信这会做您想要做的事情:
Demo: http://jsfiddle.net/maniator/rKcwP/ 演示: http : //jsfiddle.net/maniator/rKcwP/
Code: 码:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.