使用 object.create 和 new 运算符创建继承之间的区别

Difference between creating inheritance using object.create and new operator

请找出我创建继承的两种方法。谁能解释一下每种类型的情况。

方法一:

function Person(name){
    this.name = name;
}

Person.prototype.getName = function(){
    return this.name;
}

function Employee(name, designation){
    Person.call(this, name);
   this.designation = designation;
}

Employee.prototype = new Person();
Employee.prototype.constructor = Employee;

Employee.prototype.getDesignation = function(){
    return this.designation;
}

new Employee("Jagadish", "Cons");

方法二:

function Person(name){
    this.name = name;
}

Person.prototype.getName = function(){
    return this.name;
}

function Employee(name, designation){
    Person.call(this, name);
    this. designation = designation;
}

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

Employee.prototype.getDesignation = function(){
    return this.designation;
}

new Employee("Jagadish", "Cons");

我已经插入了每个对象的控制台图像。在第一种方法中,我可以在 Person class 中看到 name 属性 未定义(请参阅第一个屏幕截图)。

但是在第二种继承方法的情况下,我在 Person class 中没有 name 属性

有人可以深入解释这种行为以及后台发生的情况。

这里没有什么神奇的事情发生,程序完全按照它的指示去做。

当您调用 new Person 时,您正在创建一个新对象。该对象有一个 name 属性 因为您在函数内部明确分配给 this.name

Object.create 然而会创建一个 对象,除非它被传递给带有 属性 描述符的第二个参数。


解释一下Object.createnew A的具体区别:

new A():

  • 创建一个继承自 A.prototype
  • 的新对象
  • A应用于新对象,即调用A.call(newObj)

Object.create(A.prototype):

  • 创建一个继承自 A.prototype
  • 的新对象

所以你看,这两个调用之间的具体区别在于 new 函数应用于新对象,而 Object.create 则不是。


相关:Benefits of using `Object.create` for inheritance