gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:00:25 24 4
gpt4 key购买 nike

以下两种在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com