以下两种在 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.prototype
,this.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/