如何从子访问父变量

How to access parent variable from child

本文关键字:变量 访问      更新时间:2023-09-26

我试图从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();

如何从Item访问Parent

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();
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();