如何使用 Javascript 函数创建对象?

Ger*_*mán 0 javascript methods class object

我正在学习 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"!
}
Run Code Online (Sandbox Code Playgroud)

这就是我正在尝试的

 function createCat(name,age){
      var Cat={};
        Cat.Name=name;
        Cat.Age=age;
        Cat.meow=function(){return "Meow!"};
        return Cat;
     }
Run Code Online (Sandbox Code Playgroud)

我正在测试将脚本加载到 index.html 文件中的功能,在浏览器中打开该文件,然后在 Web 控制台中测试该功能。我运行该函数没有问题。然后,我测试 Cat 对象是否是通过在控制台中写入 Cat.Name 返回的,这会导致错误。当我在下面的一行代码中调用该函数,然后尝试访问该对象的属性时,也会发生同样的事情。错误显示为“ReferenceError:Cat 未定义”。我究竟做错了什么?谢谢!

Kok*_*oko 5

一种更简洁的方法是完全省略该let Cat = {}部分。您可以使用该函数本身来创建Cat对象。

function Cat(name, age) {
    this.name = name;
    this.age = age;
    this.meow = () => console.log("Meow!");
}

let myCat = new Cat("Waldorf", 16)
let anotherCat = new Cat("Statler", 12)

myCat.meow()
console.log(anotherCat.name)
Run Code Online (Sandbox Code Playgroud)