繁体   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