如何访问父对象的属性?

时间:2016-01-20 19:21:50

标签: javascript

请帮助解决问题。

我制作3个物品:

级别:

var Level = function() { 
  self = this;
  this.cellsObserver = new CellsObserver();
  console.log('co from level ' + this.cellsObserver);
  this.fieldObj = new Field();
}

字段:

var Field = function() { 
  self = this;
  this.init();
};

Field.prototype = Object.create(Level.prototype);

Field.prototype = {
  init: function() {
    console.log('co from field ' + self.cellsObserver);
  } 
 } 

观察者:

var CellsObserver = function(){
  .............
}
结果控制台输出中的

如下:

  

来自[object object] co的字段来自字段undefined

我不明白为什么在第二种情况下输出' undefined'。因为我已经任命了一位家长:

Field.prototype = Object.create(Level.prototype);

2 个答案:

答案 0 :(得分:0)

您正在覆盖Field.prototype。只需分配到Field.prototype.init

答案 1 :(得分:0)

tl; dr:在Field或Level.prototype对象中既没有字段cellsObserver。在Javascript中没有经典的“自我”这样的东西。

长篇故事。

当您尝试抓取object.property时,Javascript会查看试图查找property的对象,然后查看object.prototype(这是另一个对象),依此类推,直到它到达Object.prototype引用中的null原型。

所以,当你第二次调用Level构造函数中的this.cellsObserver时,它是这样的: this是一个新构造的对象(如果使用new关键字调用),并且属性列表中有cellsObserver,因此无需深度查找即可获取它。 / p>

然后,

Field.prototype = Object.create(Level.prototype);

这仅表示Field.prototype现在将引用一个新对象,该属性与当时Level.prototype中的属性相同。 从您的代码中,Level.prototype对象中没有非标准属性(您没有提供任何属性)。

然后,

self = this;

在这里,您只需为名为self的全局变量分配对刚刚创建的对象或窗口对象(it depends)的引用。如果您希望存储对this对象的引用,则应varvar self = this。但是你应该记住,这个self变量只能在声明的范围或闭包中访问。

然后,

Field.prototype = {
  init: function() {
    console.log('co from field ' + self.cellsObserver);
  } 
 } 

首先,在这里你只需覆盖previos指令(Field.prototype = Object.create(Level.prototype);)。如果您想扩展Field.prototype对象,可以在Object.create调用in second argument中进行,或者只访问以下属性:Field.prototype.init = function(){...}

二。 self变量可以包含执行init函数时的任何内容。只需在此处使用this作为当前对象。

第三。让我们试着猜测在this.cellsObserver函数中init进行评估时会发生什么。

this对象是指Field个实例,那里没有cellsObserver属性,所以我们移动到上面定义的Field.prototype对象( { init: function () {...}}),也没有cellsObserver,因此我们转移到Object.prototype对象,即null。好的,我们的查找失败,this.cellsObserver未定义。

如果Field.prototype = Object.create(Level.prototype)没有被以下代码覆盖,它会是什么样子? this对象将尽早引用Field实例。 Field.prototype引用的对象是Level.prototype对象的副本,此处也没有cellsObserver。所以,我们期待Object.prototype,就是这样。除了Level类中的实例之外,任何对象中都没有cellsObserverField实例中没有以任何方式引用它们。

你可以在这里玩:http://www.objectplayground.com/贴上这段代码:

var Level = function() {
  this.cellsObserver = new CellsObserver();
  this.fieldObj = new Field();
}

var Field = function() {
  this.init();
};

Field.prototype = Object.create(Level.prototype);

Field.prototype.init = function() {};

this.field = new Field();
相关问题