0

我正在尝试从 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

4

2 回答 2

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();
于 2013-06-18T13:50:33.007 回答
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();
于 2013-06-18T13:52:44.140 回答