这是一个在 Codecademy 中运行良好的代码,它就是它的来源。但是,当我在浏览器中尝试相同的代码时,它始终返回未定义。
<script>
function Cat(name, breed) {
this.name = name;
this.breed = breed;
}
Cat.prototype.meow = function() {
console.log('Meow!');
};
var cheshire = new Cat("Cheshire Cat", "British Shorthair");
var gary = new Cat("Gary", "Domestic Shorthair");
alert(console.log(cheshire.meow));
alert(console.log(gary.meow));
</script>
最佳答案
您正在将 console.log()
的结果传递给 alert
,但它不会返回任何内容,因此您传递的是 undefined
> 来提醒
。
要么只使用警报
,要么只使用控制台
日志,不要将一个传递给另一个。
你的 meow
函数已经记录到控制台,所以再次执行是没有意义的。您最可能想要的是这样的:
cheshire.meow();
gary.meow();
请注意,由于 meow
是一个函数,您可能想要实际调用它,而不仅仅是打印函数本身。
关于JavaScript 原型(prototype)浏览器输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38078610/