JavaScript原型浏览器输出

JavaScript Prototype browser output

本文关键字:输出 浏览器 原型 JavaScript      更新时间:2023-09-26

这是一个在Codecademy中工作良好的代码,这就是它的来源。但是,当我在浏览器中尝试相同的代码时,它一直返回undefined。

<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传递给alert

只使用alertconsole日志,不要将一个传递给另一个。

您的meow函数已经记录到控制台,所以再做一次是毫无意义的。您想要的最有可能是:

cheshire.meow();
gary.meow();

注意,由于meow是一个函数,您可能希望实际调用它,而不仅仅是打印函数本身。