javascript继承中正确的原型做法是什么?

Off*_*rmo 5 javascript inheritance

我已经阅读了几篇关于js继承的文章(这一篇,这一篇,这一篇,等等)

在Mozilla的这篇文章中,"经典"继承如下所示:(我统一的例子)

// inherit Base
function Derived() { ... }
Derived.prototype = new Base();            <-------
Derived.prototype.constructor = Derived;   <-------
Run Code Online (Sandbox Code Playgroud)

但是在本文中我看到:

// inherit Base
function Derived() { ... }
Derived.prototype = Object.create(Base.prototype);    <-------
Derived.prototype.constructor = Derived;
Run Code Online (Sandbox Code Playgroud)

而且我也看到了这个:

Derived.prototype = Base.prototype;
Run Code Online (Sandbox Code Playgroud)

而且我也进行了实验,但未找到constructor矫揉造作的用法:

Derived.prototype.constructor = Derived; <--- it still work if I skip this line
Run Code Online (Sandbox Code Playgroud)

如果我跳过此行,无论如何都要new Derived()正确调用Derived().

那么1)什么是正确的:

  1. Derived.prototype = new Base();
  2. Derived.prototype = Object.create(Base.prototype);
  3. Derived.prototype = Base.prototype;
  4. 其他?

2)Derived.prototype.constructor = Derived;真的需要吗?为什么?

Ber*_*rgi 3

Derived.prototype = new Base();
Run Code Online (Sandbox Code Playgroud)

这确实调用Base构造函数只是为了设置原型链。虽然有时可以工作并给出与 相同的结果Object.create,但它很容易出错,应该避免。阅读Derived.prototype = new Base 处使用“new”关键字的原因是什么(以及为什么不应使用它

Derived.prototype = Object.create(Base.prototype);
Run Code Online (Sandbox Code Playgroud)

这是最先进的——可以说是正确的 javascript 继承。

Derived.prototype = Base.prototype;
Run Code Online (Sandbox Code Playgroud)

这是完全错误的不使用。它允许Base实例Derived同一个对象继承 - 虽然为“类”拥有多个构造函数(很少)会有所帮助,但这不是“子类化”。

真的Derived.prototype.constructor = Derived;需要吗?为什么?

它可以被省略,您的脚本仍然可以工作,但为了方便起见,您会期望(new Derived).constructor === Derived. 另请查看JavaScript 继承和构造函数属性