題目描述我想寫一個繼承,子類的實例能夠繼承父類的方法和屬性題目來源及自己的思路相關代碼function Animal (name) { this.name = name || 'Animal'; this.sleep = function () { console.log(this.name + '正在' + 'eatting')
}
}
Animal.prototype.eat = function (food) { console.log(this.name +'吃' + food)
}function Cat(name, food) {
Animal.call(this, name) // console.log(Animal.name, name)
this.food = food || 'meat'}
extend (Animal, Cat)function extend (subClass, superClass) {
subClass.prototype = new superClass()
subClass.prototype.constuctor = subClass //修復構造函數指向的}const cat = new Cat('haixin', 'fish')console.log(cat.name) // haixinconsole.log(cat) // Cat { name: 'haixin', sleep: [Function], food: 'fish' }//cat上面沒有Animal上原型鏈上的eat方法cat.eat() // TypeError: cat.eat is not a function你期待的結果是什么?實際看到的錯誤信息又是什么?我以為新生成的cat這個實例能夠獲得Cat和Animal上的方法和屬性,但Animal上原型鏈上的eat方法獲取不到,不知道為什么?還有為什么extend方法里subClass.prototype的constuctor屬性要重新指向subClass?
用組合繼承寫一個繼承,獲取不到父類原型鏈上的方法
胡說叔叔
2018-07-22 14:42:14