使用 object.create 设置 object 的原型

set an object's prototype using object.create

在下面的代码中,如何使用 object.create() method.I 将 child 的原型设置为 parent method.I

child.prototype=new Parent();

但我想使用 object.create 来实现。使用 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();

两期:

  1. 您定义的第一个parentFunction是在Parent的构造函数中,不是原型。所以 Parent.prototype.parentFunction 没有定义。相反,对于 Parent.

  2. 的每个实例,都有一个单独的 parentFunction 副本
  3. Child构造函数中,this.constructor.prototype指的是Child的原型,不是Parent的原型。如果您想要 Parent 原型,可以使用 this.prototype.prototype.

  4. 访问

我对您的代码进行了最低限度的修改,以便对子项调用 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();