Javascript I';我对call()感到困惑,为什么';我的代码不工作吗?
我想调用一个来自哺乳动物的函数,用于Cat。我以为我理解它,但每次我尝试使用它时,我都会感到困惑Javascript I';我对call()感到困惑,为什么';我的代码不工作吗?,javascript,method-call,Javascript,Method Call,我想调用一个来自哺乳动物的函数,用于Cat。我以为我理解它,但每次我尝试使用它时,我都会感到困惑 function Mammal(legs,sound, commonName) { this.legs = legs; this.sound = sound; this.commonName = commonName; this.talk = function() { console.log(this.sound); } } const wo
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');
我想在lion的背景下使用talk。你是suuuper close。您只需要在哺乳动物调用()函数中添加参数
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())
我把哺乳动物改成了哺乳动物。叫(这个,说话)。叫(这个,腿,声音,名字)
我希望这就是你想要的!如果不是,请告诉我
编辑:我还注意到,我将“talk”函数中的console.log()替换为“returnthis.sound”,然后替换了我正在执行的最后一行“console.log(lion.talk())”您已经非常接近了。您只需要在哺乳动物调用()函数中添加参数
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())
我把哺乳动物改成了哺乳动物。叫(这个,说话)。叫(这个,腿,声音,名字)
我希望这就是你想要的!如果不是,请告诉我
编辑:我还注意到,我将“talk”函数中的console.log()替换为“return this.sound”,然后是我正在执行的最后一行“console.log(lion.talk())”
哺乳动物.call(this,talk)
调用一个需要(legs,sound,commonName)
值talk
(这是一个断章取义的引用–在这里没有所谓的talk
)。你想让哺乳动物调用(this,talk)
做什么?你实际上想做什么?你想让cat.talk()
调用与dog.talk()
相同的函数吗?哺乳动物调用(this,talk)
调用一个函数,该函数期望(腿、声音、commonName)
的值为talk
(这是一个断开的引用-在范围内没有被称为talk
)。你想让哺乳动物调用(this,talk)
做什么?你实际上想做什么?你想让cat.talk()
调用与dog.talk()相同的函数
?调用之前不需要执行3个赋值,因为这与哺乳动物的构造函数是一样的。@Barmar肯定没有。但听起来他好像刚开始使用javascript,想熟悉随机的东西来理解这个概念。在这种情况下,我想是它的设置变量吧?“_(ツ)_/“‘只要能帮助人们学习基础知识就行了。在调用之前,不需要执行这3个赋值,因为它与哺乳动物构造函数是一样的。@Barmar肯定没有。但听起来他好像刚开始使用javascript,想熟悉随机的东西来理解这个概念。在这种情况下,它的sett我想,是因为变量太小了吧_(ツ)_/''任何有助于人们学习基础知识的东西。