亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Javascript 函數創建對象?

如何使用 Javascript 函數創建對象?

至尊寶的傳說 2023-07-06 11:06:26
我正在學習 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 未定義”。我究竟做錯了什么?謝謝!
查看完整描述

4 回答

?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

一種更簡潔的方法是完全省略該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)


查看完整回答
反對 回復 2023-07-06
?
森林海

TA貢獻2011條經驗 獲得超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)


查看完整回答
反對 回復 2023-07-06
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

您會收到此錯誤,因為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);


查看完整回答
反對 回復 2023-07-06
?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

如果你想在控制臺上輸入時獲得你的 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);




查看完整回答
反對 回復 2023-07-06
  • 4 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號