[英]javascript OOP get from parent object
我該如何訪問子對象的父屬性?
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'
如何訪問
this.obj
的子對象?
你不能
有一個baz
不管有多少new foo
也有,所以沒有辦法從地圖this
通常指向單foo.prototype.baz
到的特定實例foo
。
看來您可能打算為foo
每個實例創建一個baz
。
嘗試這個
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);
}
嘗試像這樣定義
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.