在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 用組合繼承寫一個繼承,獲取不到父類原型鏈上的方法

用組合繼承寫一個繼承,獲取不到父類原型鏈上的方法

題目描述

我想寫一個繼承,子類的實例能夠繼承父類的方法和屬性

題目來源及自己的思路

相關代碼

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 //修復構(gòu)造函數(shù)指向的
}
const cat = new Cat('haixin', 'fish')
console.log(cat.name) // haixin
console.log(cat) // Cat { name: 'haixin', sleep: [Function], food: 'fish' }
//cat上面沒有Animal上原型鏈上的eat方法
cat.eat() // TypeError: cat.eat is not a function

你期待的結(jié)果是什么?實際看到的錯誤信息又是什么?

我以為新生成的cat這個實例能夠獲得Cat和Animal上的方法和屬性,但Animal上原型鏈上的eat方法獲取不到,不知道為什么?還有為什么extend方法里subClass.prototype的constuctor屬性要重新指向subClass?

回答
編輯回答
神經(jīng)質(zhì)
  1. 因為你這句寫反了 extend (Animal, Cat), 應該是先子類再父類,即正確的是 extend (Cat, Animal).
  2. subClass.prototype的constuctor屬性要重新指向subClass?
    new Cat后,得到一個cat實例,你咋知道它是那個類創(chuàng)建的,就是通過訪問 cat.constructor 得知來自于類 Cat。
    實際cat實例本身沒有這個屬性,它是通過自身的__proto__屬性指向父類的prototype屬性,即Cat.prototype, 然后找到其中的contructor返回的。
2018年3月17日 16:27