javascript继承中正确的原型实现是什么? [英] What is the correct prototype affectation in javascript inheritance?
问题描述
我已经阅读了几篇关于js继承的文章(这一篇,这一个,这个等。)
I read several articles on js inheritance already (this one, this one, this one, etc.)
在本文,经典继承如下所示:(我统一化的例子)
In this article from Mozilla, "classic" inheritance is shown as this : (I uniformized examples)
// inherit Base
function Derived() { ... }
Derived.prototype = new Base(); <-------
Derived.prototype.constructor = Derived; <-------
但是在这篇文章我看到:
// inherit Base
function Derived() { ... }
Derived.prototype = Object.create(Base.prototype); <-------
Derived.prototype.constructor = Derived;
此外我也看到过:
Derived.prototype = Base.prototype;
我还试验过,无法找到构造函数的使用
影响:
And I also experimented and couldn't find the use of constructor
affectation :
Derived.prototype.constructor = Derived; <--- it still work if I skip this line
如果我跳过此行, new Derived()
无论如何正确地调用 Derived()
。
if I skip this line, new Derived()
correctly calls Derived()
anyway.
所以1)什么是正确的:
So 1) what is correct :
-
Derived.prototype = new Base();
-
Derived.prototype = Object.create(Base.prototype);
-
Derived.prototype = Base.prototype;
- 其他?
Derived.prototype = new Base();
Derived.prototype = Object.create(Base.prototype);
Derived.prototype = Base.prototype;
- other ?
和2)是 Derived.prototype.constructor = Derived;
真的需要吗?为什么?
And 2) is Derived.prototype.constructor = Derived;
really needed ? Why ?
推荐答案
Derived.prototype = new Base();
这会调用 Base
构造函数仅用于设置原型链。虽然有时工作并给予 Object.create
等效的结果,但它容易出错,应该避免。阅读使用'new'关键字的原因是什么在Derived.prototype = new Base (以及它不的原因)。
This does call the Base
constructor just for setting up the prototype chain. While sometimes working and giving equivalent results to Object.create
, it is error-prone and should be avoided. Read What is the reason to use the 'new' keyword at Derived.prototype = new Base (and why it should not be used).
Derived.prototype = Object.create(Base.prototype);
这是最先进的 - 更正javascript继承这样说。
This is state of the art - Correct javascript inheritance so to say.
Derived.prototype = Base.prototype;
这是完全错误的。 不要使用。它允许 Base
和派生
实例从相同的对象继承 - 而它(很少)对于类有多个构造函数可能会有所帮助,这不是子类化。
This is plain wrong. Do not use. It lets Base
and Derived
instances inherit from the same object - while it (seldom) can be helpful to have multiple constructors for a "class", this is not "subclassing".
派生.prototype.constructor = Derived;
真的需要吗?为什么?
Is
Derived.prototype.constructor = Derived;
really needed? Why?
它可以省略,但你的脚本仍然有用,但为方便起见,你会期望( new Derived).constructor === Derived
。另请参阅 JavaScript继承和构造函数属性
It can be omitted and your script will work nonetheless, but for convenience you would expect that (new Derived).constructor === Derived
. Also have a look at JavaScript inheritance and the constructor property
这篇关于javascript继承中正确的原型实现是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!