鍍金池/ 問(wèn)答/HTML/ 用組合繼承寫(xiě)一個(gè)繼承,獲取不到父類(lèi)原型鏈上的方法

用組合繼承寫(xiě)一個(gè)繼承,獲取不到父類(lèi)原型鏈上的方法

題目描述

我想寫(xiě)一個(gè)繼承,子類(lèi)的實(shí)例能夠繼承父類(lèi)的方法和屬性

題目來(lái)源及自己的思路

相關(guān)代碼

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 //修復(fù)構(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上面沒(méi)有Animal上原型鏈上的eat方法
cat.eat() // TypeError: cat.eat is not a function

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

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

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