鉴于这段代码:
var SuperClass = function(a, b) {
this.a = a;
this.b = b;
};
SuperClass.prototype.getA = function() {
return this.a;
};
var SubClass = function(a, b, c) {
SuperClass.call(this, a, b);
this.c = c;
};
Run Code Online (Sandbox Code Playgroud)
为了启动SubClass原型,大多数建议似乎如下:
SubClass.prototype = new SuperClass();
Run Code Online (Sandbox Code Playgroud)
对我来说,创建(实例化)一个新SuperClass对象(具有自己的属性a和b属性)似乎很奇怪,只是作为它的原型SubClass.
这也有效:
// anti-pattern
SubClass.prototype = SuperClass.prototype;
Run Code Online (Sandbox Code Playgroud)
但它通过SuperClass.prototype引用传递对象,因此您添加到的任何内容SubClass.prototype也会添加到SuperClass.prototype,因为它们是同一个对象.在大多数情况下,这不是预期的行为.
问题:有没有办法实现正确的原型设计而不创建一个实例SuperClass作为SubClass基础原型?
在现代浏览器下:
SubClass.prototype = Object.create( SuperClass.prototype );
Run Code Online (Sandbox Code Playgroud)
这使您可以创建具有已定义的对象,而无需调用父类的"构造函数"方法.有关更多详细信息,请阅读(包括旧版浏览器的polyfill实现).__proto__ Object.create
看到行动:
function Foo(){ console.log("AHHH!"); }
Foo.prototype.foo = 42;
function Bar(){}
Bar.prototype = Object.create(Foo.prototype); // Note: no "AHHH!" shown
Bar.prototype.bar = 17;
// Showing that multi-level inheritance works
var b = new Bar;
console.log(b.foo,b.bar); //-> 42, 17
// Showing that the child does not corrupt the parent
var f = new Foo; //-> "AHHH!"
console.log(f.foo,f.bar); //-> 42, undefined
// Showing that the inheritance is "live"
Foo.prototype.jim = "jam";
console.log(b.jim); //-> "jam"
Run Code Online (Sandbox Code Playgroud)