经典继承
借用构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| function Super(name){ this.name = name; this.colors = ['red', 'green', 'white']; }
Super.prototype.say= function () { console.log(this.name); }
function Sub(name) { Super.call(this,name); }
var a = new Sub("a"); a.colors.push("yellow"); var b = new Sub("b");
console.log(a); console.log(b);
a.say();
|
优点: 隔离了超类的共享属性
缺点: 无法复用父类原型方法
原型链继承
原型链
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
function Super(name){ this.name = name; this.colors = ['red', 'green', 'white']; }
Super.prototype.say= function () { console.log(this.name); }
function Sub(name) { this.name = name }
Sub.prototype = new Super();
var a = new Sub(); a.colors.push("yellow"); var b = new Sub();
console.log(a.__proto__); console.log(b.__proto__); a.say();
|
优点:继承了超类原型方法
缺点:超类中的引用属性做不到隔离
组合试继承
结合经典继承与原型链继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function Super(name){ this.name = name; this.colors = ['red', 'green', 'white']; }
Super.prototype.say= function () { console.log(this.name); }
function Sub(name,age) { Super.call(this,name); this.age = age; }
Sub.prototype = new Super();
var a = new Sub("a",21); a.colors.push("yellow"); var b = new Sub("b",22);
console.log(a); console.log(b); a.say();
|
优点:隔离超类引用类型属性,复用原型方法
缺点:超类构造函数被调用2次
寄生式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
var Super = { name: '12', colors:['red', 'green', 'white'] }
function Sub(obj) {
var a = Object.create(obj); return a }
var a = new Sub(Super); a.colors.push("yellow"); var b = new Sub(Super);
console.log(a.__proto__); console.log(b.__proto__);
|
寄生组合式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function Super(name){ this.name = name; this.colors = ['red', 'green', 'white']; }
Super.prototype.say= function () { console.log(this.name); }
function Sub(name,age) { Super.call(this,name); this.age = age; }
function inheritPrototype(Sub, Super) { var proto = Object.create(Super.prototype); proto.constructor = Sub; Sub.prototype = proto; }
inheritPrototype(Sub, Super);
var a = new Sub("a",21); a.colors.push("yellow"); var b = new Sub("b",22);
console.log(a); console.log(b); a.say();
|