我正在尝试从B中访问A中的变量(在我的示例中)。 我没有从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();
如何从Parent
访问Item
?
答案 0 :(得分:0)
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();
答案 1 :(得分:0)
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();