【发布时间】:2020-11-02 18:40:56
【问题描述】:
我正在学习 JavaScript 课程。我在“对象和类”一章,我不知道如何解决作业中的一些作业。 第一个练习是这样的
function createCat(name,age){
//Create a new object with the property "name" and the value defined by the argument "name".
//Add a new property to the object with the name "age" and use the value defined by the argument"age"
//Add a methos (function) called meow that returns the string "Meow"!
}
这就是我正在尝试的
function createCat(name,age){
var Cat={};
Cat.Name=name;
Cat.Age=age;
Cat.meow=function(){return "Meow!"};
return Cat;
}
我正在测试将脚本加载到 index.html 文件中的函数,在浏览器中打开该文件,然后在 Web 控制台中测试这些函数。我运行该功能,没有问题。然后,我通过在控制台中写入 Cat.Name 来测试是否返回了 Cat 对象,这会导致错误。当我在下面的一行代码中调用函数然后尝试访问 Object 的属性时,也会发生同样的事情。错误显示为“ReferenceError: Cat is not defined”。我究竟做错了什么?谢谢!
【问题讨论】:
标签: javascript class object methods