猿问

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

我正在学习 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 对象是否是通过在控制台中写入 Cat.Name 返回的,这会导致错误。当我在下面的一行代码中调用该函数,然后尝试访问该对象的属性时,也会发生同样的事情。错误显示为“ReferenceError:Cat 未定义”。我究竟做错了什么?谢谢!


至尊宝的传说
浏览 143回答 4
4回答

人到中年有点甜

一种更简洁的方法是完全省略该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)

森林海

您的函数返回 Cat,但这只是函数作用域中的一个名称。为了在函数中使用该名称,您需要执行以下操作:function createCat(name, age) {        var cat = {};        cat.Name = name;        cat.Age = age;        cat.meow = () => "Meow!";        return cat;}let Cat = createCat("mist", 16);console.log(Cat)

温温酱

您会收到此错误,因为Cat仅在您的函数范围内定义。要Cat全局定义,请使用window.Cat而不是var Cat:function createCat(name, age) {  window.Cat = {};  Cat.Name = name;  Cat.Age = age;  Cat.meow = function() {    return "Meow!"  };  return Cat;}console.log(Cat.Name);

米琪卡哇伊

如果你想在控制台上输入时获得你的 Cat,Cat.name你必须像这样全局声明它:function createCat(name, age) {  return {    name: name,    age: age,    meow: function() {      return "Meow!"    },  };}window.Cat = createCat('name', 2);然后您就可以在全球范围内访问您的 Cat。您还可以将 Cat 分配给浏览器控制台上的变量并通过Cat.name如下方式访问它:const Cat = createCat('name', 2);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答