【问题标题】:set an object's prototype using object.create使用 object.create 设置对象的原型
【发布时间】:2015-01-15 16:22:54
【问题描述】:

i was answering to a question where i encountered this problem 在下面的代码中,如何使用 object.create() 方法将孩子的原型设置为父级。我可以使用

child.prototype=new Parent();

但我想使用 object.create.using child.prototype=Object.create(Parent) 来实现,但没有将原型设置为 Parent

function Parent() {
   this.parentFunction = function(){
      console.log('parentFunction');
   }
}
Parent.prototype.constructor = Parent;

function Child() {

   this.parentFunction = function() {

      this.constructor.prototype.parentFunction.call(this);
      console.log('parentFunction from child');
   }
}
Child.prototype = Object.create(Parent);
Child.prototype.constructor = Child;

var child = new Child();
console.dir(child);
child.parentFunction();

【问题讨论】:

  • Object.create 使用给定的原型创建一个新对象。你已经有一个对象,你只是想改变它的原型,所以Object.create 似乎只是改变原型的错误方法。
  • Child.prototype = Object.create(Parent.prototype);。尽管这样做没有任何价值,因为您没有向Parent.prototype 添加任何内容。您还缺少其他东西。看看Benefits of using Object.create for inheritance
  • @FelixKling 谢谢!!但请你详细说明!!我还没有定义父母的原型。声明似乎令人困惑
  • 看看另一个问题,我想我的回答解释了你需要知道的一切。 Object.create(Parent) 将创建一个在其原型链中具有 函数 Parent 的新对象。那不是你想要的。理想情况下,parentFunction 将在 Parent.prototype 上定义。
  • 我建议您在 Child-Constructor 中使用 Parent.call(this) 以便能够以实例继承方式继承父方法。

标签: javascript prototype prototype-chain


【解决方案1】:

两个问题:

  1. 您定义的第一个parentFunctionParent 的构造函数中,不是原型。所以Parent.prototype.parentFunction 没有定义。相反,对于 Parent 的任何实例,都有一个单独的 parentFunction 副本。

  2. Child构造函数中,this.constructor.prototype指的是Child的原型,而不是Parent的原型。如果您想要 Parent 原型,可以使用 this.prototype.prototype 访问。

我对您的代码进行了最低限度的修改,以便对子级调用 parentFunction 对父级调用 parentFunction

function Parent() {

}

Parent.prototype.parentFunction = function(){
      console.log('parentFunction in parent');
}


Parent.prototype.constructor = Parent;

function Child() {

}

Child.prototype = Object.create(Parent);
Child.prototype.parentFunction = function() {
      this.prototype.parentFunction.call();
      console.log('parentFunction from child');
};
Child.prototype.constructor = Child;

var child = new Child();
console.dir(child);
child.parentFunction();

【讨论】:

  • 它和我的代码一样,但方式不同?你能指出为什么我提供的代码失败了吗??
  • 当然。我在答案的顶部进行了解释。在您的代码中,Parent 原型中没有 parentFunction,因为您在构造函数中分配给 thisthis 是对当前对象的引用,不是对原型的引用,因此原型永远不会被分配parentFunction 属性。在我的版本中,我将属性分配给原型。第二个问题是您访问Child 实例原型的原型的代码不正确:应该是this.prototype 而不是this.construtor.prototype
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 2012-06-29
  • 1970-01-01
相关资源
最近更新 更多