簡體   English   中英

Javascript Object 方法值未與 object 的 console.log 一起顯示

[英]Javascript Object method value not showing with console.log of the object

我對 JavaScript 中的對象有點困惑......

我寫了一個 object:

 const gix = { firstName: "John", lastName: "Johnson", yearOfBirth: 2000, profession: "IT", friends: ["Mark", "Luke", "John"], driversLicence: true, age: function () { this.calcAge = 2022 - this.yearOfBirth; return this.calcAge; }, }; gix.age(); console.log(gix);

為什么整個 object 的控制台日志不顯示計算值但顯示年齡:f()

考慮到您的用例,您可以用getter替換該方法,每次引用 object 時都會對其進行評估:

const gix = {
  firstName: "John",
  lastName: "Johnson",
  yearOfBirth: 2000,
  profession: "IT",
  friends: ["Mark", "Luke", "John"],
  driversLicence: true,
  get age() {
    return 2022 - this.yearOfBirth;
  },
};

您要么想要捕獲 function 的返回值,要么這樣稱呼它:

console.log(gix.age());

將年齡視為指向 function 的指針......

When you're console logging a function it wont execute it, It will just show the contents of the function, IF you need to see the value then you need to call the function and log the output

console.log(gix.age());

如果您檢查日志,它實際上添加了calcAge ,因為您之前已經調用了age 如果你想使用yearOfBirth的計算屬性calcAge ,你可以使用 Object getter

 const gix = { firstName: "John", lastName: "Johnson", yearOfBirth: 2000, profession: "IT", friends: ["Mark", "Luke", "John"], driversLicence: true, get calcAge () { return 2022 - this.yearOfBirth; }, }; console.log(gix.calcAge);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM