- 原型鏈繼承,缺點:引用類型屬性list改了,會影響其他實例
function Super() {
this.list = [1,2]
}
Super.prototype.sayAge = function () {
console.log(this.age)
}
function Sub(age) {
this.age = age;
}
Sub.prototype = new Super()
var s1 = new Sub(30)
s1.list.push(3)
var s2 = new Sub(30)
s2.list // [1,2,3]
- 借用構造函數(shù),函數(shù)被call來使用,無法繼承函數(shù)的原型
function Super() {
this.list = [1,2]
}
Super.prototype.sayAge = function () {
console.log(this.age)
}
function Sub(age) {
this.age = age;
Super.call(this)
}
var s1 = new Sub(30)
s1.sayAge // undefined
- 組合繼承;結合上面的兩個繼承,互補利弊;唯一不足,實例通過Super.call有的屬性,原型上 new Super()也有,重復了
function Super(name) {
this.name = name
this.list = [1,2]
}
Super.prototype.sayAge = function () {
console.log(this.age)
}
function Sub(name, age) {
Super.call(this, name)
this.age = age;
}
Sub.prototype = new Super()
var s1 = new Sub('kp', 30)

s1原型上,屬性重復
- 寄生組合式繼承,Sub.prototype是一個空對象new F()【代替new Super()】這個空對象的構造函數(shù)原型是Super.prototype;解決上面問題: 原型上 new Super()也有,重復了 的問題
function object(o){
function F(){}
F.prototype = o;
return new F();
}
function Super(name) {
this.name = name
this.list = [1,2]
}
Super.prototype.sayAge = function () {
console.log(this.age)
}
function Sub(name, age) {
Super.call(this, name)
this.age = age;
}
Sub.prototype = object(Super.prototype)
// Sub.prototype = Object.create(Super.prototype) // 上一行代碼,可以用Object.create,代替object這個自定義方法
Sub.prototype.constructor = Sub
var s1 = new Sub('kp', 30)
s1

s1原型上,沒有重復屬性
- class 繼承,采用的就是 【4. 寄生組合式繼承】
class Super{
constructor(name) {
this.name = name
}
sayAge() {
console.log(this.age)
}
}
class Sub extends Super{
constructor(name, age) {
super(name)
this.age = age
}
}
var s1 = new Sub('kp', 30)

s1 - class繼承