【问题标题】:How do you use a function to create an Object with Javascript?您如何使用函数通过 Javascript 创建对象?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 我同意这是一个更好的答案。
    【解决方案2】:

    您的函数返回 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)

    【讨论】:

      【解决方案3】:

      您收到此错误是因为 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);

      【讨论】:

      • 这个答案其实是不正确的,因为现在函数每次调用都会覆盖window.Cat...
      • 这是在函数之外调用 Cat 的唯一方法。这不是要求(根据练习要求),但它是 OP 收到错误的主要原因。
      • OP 的函数返回一只猫,因此将返回的猫存储在变量中更有意义。例如:let cat = createCat("Jonesy", 10)。这样猫就可以在全局范围内使用,并且您可以拥有不止一只不同的猫。
      【解决方案4】:

      如果您想在控制台Cat.name 上键入时获取您的 Cat,您必须像这样全局声明它:

      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);

      【讨论】:

        猜你喜欢
        • 2014-01-26
        • 2012-04-07
        • 2018-10-01
        • 1970-01-01
        • 2020-11-18
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 2011-10-25
        相关资源
        最近更新 更多