我对call()感到困惑,为什么我的代码不起作用?

时间:2019-10-11 22:04:07

标签: javascript method-call

我想从Mammal调用一个函数,以便与Cat一起使用。我以为我了解它,但是每次尝试使用它时,我都会感到非常困惑。

function Mammal(legs,sound, commonName) {
    this.legs = legs;
    this.sound = sound;
    this.commonName = commonName;
    this.talk = function() {
        console.log(this.sound);
    }
}

const wolf = new Mammal(4, 'GRRRRRR', 'Wolf');

const dog = new Mammal(4, 'WOOF', 'Dog');

console.log(wolf)
console.log(dog.talk())

const cat = function(legs, sound, commonName) {
this.legs = legs;
this.sound = sound;
this.commonName = commonName;
Mammal.call(this, talk)
}

const lion = new cat(4, 'RAWR', 'Lion');

我想在狮子的背景下使用谈话。

1 个答案:

答案 0 :(得分:2)

你是suuuper关闭。您只需要在Mammal.call()函数中添加参数即可。

function Mammal(legs,sound, commonName) {
    this.legs = legs;
    this.sound = sound;
    this.commonName = commonName;
    this.talk = function() {
        return this.sound;
    }
}

const wolf = new Mammal(4, 'GRRRRRR', 'Wolf');

const dog = new Mammal(4, 'WOOF', 'Dog');

const cat = function(legs, sound, commonName) {
    this.legs = legs;
    this.sound = sound;
    this.commonName = commonName;
    Mammal.call(this, legs, sound, commonName);
}

const lion = new cat(4, 'RAWR', 'Lion');

console.log(lion.talk())

我将Mammal.call(this,talk)更改为Mammal.call(this,legs,sound,commonName)。

我希望这就是您要的!让我知道是否可以。

编辑:我也刚刚注意到,我在“ talk”函数中替换了console.log()以“返回this.sound”,然后我正在做的最后一行是“ console.log(lion.talk) ())”