javascript - JavaScript 中的伪经典继承与代理函数继承

标签 javascript

以下两种在 JavaScript 中实现类继承的方式有什么区别?

function Super () {
}

function Sub() {
}
Sub.prototype = new Super();

对比

Function.prototype.inherits = function inherits(ParentClass) {
    function Surrogate () {};
    Surrogate.prototype = ParentClass.prototype;
    this.prototype = new Surrogate();
}

具体来说,对于使用代理函数的第二个示例,我们为什么不能直接使用:

Function.prototype.inherits = function inherits(ParentClass) {
    this.prototype = new ParentClass();
}

我认为通过在 ParentClass() 上调用 new 并将其设置为 this.prototypethis.prototype 然后指向 ParentClass.prototype,因此继承自后者。

最佳答案

Specifically, for the second example using a surrogate function, why can't we just use [...]

Surrogate 方式基本上是 Object.create 的填充程序。 ,现代的做法是

Sub.prototype = Object.create(Super.prototype);

如果您需要在实例上调用Super的构造函数,

function Sub() {
    // an instanceof check here
    Super.apply(this);
    // construct Sub as desired
}
<小时/>

不使用Super实例作为Sub原型(prototype)的优点是我们可以更好地控制Sub实例并且不这样做不会因意外的共享值而导致奇怪的错误,

考虑以下因素

function Foo() {
    this.bar = [];
}

function Fizz() {}
Fizz.prototype = new Foo();

var a = new Fizz(),
    b = new Fizz();
a.bar.push('Hello world!');
// What is b.bar?
b.bar; // ["Hello world!"], we are sharing with `a`

对比

function Foo() {
    this.bar = [];
}

function Fizz() {
    Foo.apply(this);
}
Fizz.prototype = Object.create(Foo.prototype);

var a = new Fizz(),
    b = new Fizz();
a.bar.push('Hello world!');
// What is b.bar?
b.bar; // [], `b` has some privacy at last

关于javascript - JavaScript 中的伪经典继承与代理函数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31258980/

相关文章:

javascript - jQuery - 无法同时使用导入的文件和自己的函数

javascript - 检查全局变量是否存在的正确方法是什么?

javascript - 创建了一个选项卡但点击后无法正常工作 - jQuery 问题/新手

javascript - 如何在 JavaScript 中创建提前输入功能

javascript - 当调用返回相同对象的函数时,无论是否作为构造函数调用,我是否应该使用 `new` ?

javascript - 在 JavaScript 文件中放置字符集不起作用

javascript - Javascript递归调用中的增量(i++)和(i+=1)

javascript - 如何通过 react 上下文api传递多个状态

javascript - 错误解析SDK : Cannot sign up user with an empty name

javascript - 如何禁用导航覆盖中的主体滚动并在主体中启用它?