[英]How to access parent variable from child
I am trying to access a variable in A from B (in my example bellow). 我正在尝试从B访问A中的变量(在下面的示例中)。 I didn't extend B from A, because A is just a container.
我没有从A扩展B,因为A只是一个容器。
function A() {
var Parent = this;
this.container = [];
}
A.prototype.add = function(Item) {
Parent.container.push(Item);
}
function B() {
}
B.prototype.exec = function() {
console.log(Parent.container[0]) //Uncaught ReferenceError: Parent is not defined
}
var Manager = new A();
var Item = new B();
Manager.add(B);
Item.exec();
How to access Parent
from Item
? 如何从
Item
访问Parent
?
function A() {
this.container = [];
}
A.prototype.add = function(Item) {
this.container.push(Item);
}
function B(Parent) {
this.Parent = Parent;
}
B.prototype.exec = function() {
console.log(this.Parent.container[0]) //Uncaught ReferenceError: Parent is not defined
}
var Manager = new A();
var Item = new B(Manager);
A.add(B);
B.exec();
function A() {
this.container = [];
}
A.prototype.add = function(Item) {
//assigning parent property only if Item is added
Item.Parent = this;
this.container.push(Item);
}
function B() {
this.Parent = null;
}
B.prototype.exec = function() {
console.log(this.Parent.container[0])
}
var Manager = new A();
var Item = new B();
Manager.add(Item);
Item.exec();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.