这两种继承方式有区别吗?
Is there a difference between these 2 ways of inheritance?
问题是当我们想要建立继承时,我看不出这两种方法有什么区别:
Child.prototype = Object.create( Father.prototype );
Child.prototype.constructor = Child;
和:
Child.prototype.__proto__ = Father.prototype;
第一个选项允许我们获取父亲共享的所有属性和方法,但在此过程中覆盖子构造函数。这就是我们需要再次将 Child 构造函数设置回 Child 的原因。第二种方法做同样的事情,但没有覆盖。那么,为什么 people/Guides 不使用第二个选项呢?我有什么错吗?
这是一个完整的例子:
function Father( name ) {
this.name = name;
}
Father.prototype.getName = function() {
console.log( this.name );
}
function Child( name, lastName ) {
Father.call( this, name );
this.lastName = lastName;
}
Child.prototype.__proto__ = Father.prototype;
//Child.prototype = Object.create( Father.prototype );
//Child.prototype.constructor = Child;
var c = new Child( 'Will' , 'Travolta');
c.getName();
I don't see a difference between these 2 methods
结果确实没有区别(除了次要细节,例如 .constructor
属性 的可枚举性)。
So, why people/Guides don't use the second option?
因为 , while Object.create
在任何地方都适用。它是用 ES5 标准化的,可以很容易地为旧环境填充。
从 ES6 开始,你也可以使用 Object.setPrototypeOf
,但从 ES6 开始,你只需要写 class Child extends Father { … }
。
如评论中所写,__proto__
目前已弃用,取而代之的是 Object.getPrototypeOf()
和 Object.setPrototypeOf()
。除此之外,还有很多关于完全覆盖构造函数原型与单独 adding/removing properties/methods to/from 的正确性的公开讨论。这两种做法都广泛 accepted/implemented 并且在大多数情况下销毁 prototype.constructor
(或一个对象的所有原型)是没有害处的。我更喜欢个人操纵,因为它应该是未来的证明。请注意,写 Child.prototype = Object.create(Father.prototype)
您正在破坏原始原型。
问题是当我们想要建立继承时,我看不出这两种方法有什么区别:
Child.prototype = Object.create( Father.prototype );
Child.prototype.constructor = Child;
和:
Child.prototype.__proto__ = Father.prototype;
第一个选项允许我们获取父亲共享的所有属性和方法,但在此过程中覆盖子构造函数。这就是我们需要再次将 Child 构造函数设置回 Child 的原因。第二种方法做同样的事情,但没有覆盖。那么,为什么 people/Guides 不使用第二个选项呢?我有什么错吗?
这是一个完整的例子:
function Father( name ) {
this.name = name;
}
Father.prototype.getName = function() {
console.log( this.name );
}
function Child( name, lastName ) {
Father.call( this, name );
this.lastName = lastName;
}
Child.prototype.__proto__ = Father.prototype;
//Child.prototype = Object.create( Father.prototype );
//Child.prototype.constructor = Child;
var c = new Child( 'Will' , 'Travolta');
c.getName();
I don't see a difference between these 2 methods
结果确实没有区别(除了次要细节,例如 .constructor
属性 的可枚举性)。
So, why people/Guides don't use the second option?
因为 Object.create
在任何地方都适用。它是用 ES5 标准化的,可以很容易地为旧环境填充。
从 ES6 开始,你也可以使用 Object.setPrototypeOf
,但从 ES6 开始,你只需要写 class Child extends Father { … }
。
如评论中所写,__proto__
目前已弃用,取而代之的是 Object.getPrototypeOf()
和 Object.setPrototypeOf()
。除此之外,还有很多关于完全覆盖构造函数原型与单独 adding/removing properties/methods to/from 的正确性的公开讨论。这两种做法都广泛 accepted/implemented 并且在大多数情况下销毁 prototype.constructor
(或一个对象的所有原型)是没有害处的。我更喜欢个人操纵,因为它应该是未来的证明。请注意,写 Child.prototype = Object.create(Father.prototype)
您正在破坏原始原型。