【问题标题】:Difference between creating inheritance using object.create and new operator使用 object.create 和 new 运算符创建继承的区别
【发布时间】:2015-03-25 20:24:02
【问题描述】:

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

方法一:

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 类 中看到未定义的 name 属性(请参阅第一个屏幕截图)。

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

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

【问题讨论】:

    标签: javascript inheritance prototype prototypal-inheritance


    【解决方案1】:

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

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

    Object.create 但是会创建一个 empty 对象,除非它传递了带有属性描述符的第二个参数。


    解释Object.create和new 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

    【讨论】:

    • 感谢您的回答,但我仍然很困惑。我想知道这个语句 Person.call(this, name);正在 Employee 类中创建名称属性
    • 您只是不熟悉call 的作用吗?它执行该函数并将其this 值设置为第一个传递的参数。如果您有var obj = {}; Person.call(obj, 'foo');,则name 属性设置为obj。
    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多