//1.原型鏈繼承 var supClass = function(name, sex) { this.name = name || 'red' this.sex = sex || 'good' this.father = 'father' this.say = function() { console.log(this.name) } } supClass.prototype = { sayHi() { console.log(this.name + ' hi') } } /*var sonClass = function(name, sex) { this.name = name this.sex = sex } console.log(sonClass.prototype) sonClass.prototype = new supClass() //核心代碼 sonClass.prototype.constructor = sonClass//核心代碼 var son1 = new sonClass('red', 's') son1.say()*/ //優勢: 簡單,容易實現 //缺點: 多拷貝了一份supClass的屬性過來,而且supClass的方法每生成一個新的 // sonClass就要再從新拷貝一份,形成了沒必要要的浪費 //2.構造函數繼承 /*var sonClass = function(name, sex, type) { supClass.call(this) this.type = type this.sex = sex this.name = name } var son1 = new sonClass('jay', 'man', 'goodman') son1.say()*/ //優勢: 簡單,容易實現,能夠同時繼承多個父對象(三姓家奴) //缺點: 只能繼承定義在父元素上的屬性或方法,而對於父元素原型對象上的屬性或方法 //則沒法繼承 //3.混合繼承 /*var sonClass = function(name, sex, type) { supClass.call(this) this.type = type this.sex = sex this.name = name } sonClass.prototype = new supClass() sonClass.prototype.constructor = sonClass var son1 = new sonClass('jay', 'man', 'goodman') son1.say() son1.sayHi()*/ //優勢: 幾乎完美 //缺點: 實現複雜,使用原型繼承的部分仍然沒有解決會多拷貝一份父類屬性從而形成 //沒必要要的空間浪費的問題(能夠在sonClass的prototype中看到被屏蔽的繼承自父類的屬性) //4.寄生組合式繼承 //使用工廠函數將父元素的原型剝離出來單獨賦值給子元素的原型 function birth(f, s) { var prototype = Object(f.prototype) s.prototype = prototype s.prototype.constructor = s } //組合式繼承 /*var sonClass = function(name, sex, type) { supClass.call(this) this.type = type this.sex = sex this.name = name } birth(supClass, sonClass) var son1 = new sonClass('jay', 'man', 'goodman') son1.say() son1.sayHi()*/ //優勢: 完美 //缺點: 實現困難