【问题标题】:construct object in realtime with IIFE as method [duplicate]使用IIFE作为方法实时构造对象[重复]
【发布时间】:2021-01-08 16:24:44
【问题描述】:

当我希望属性打印年份时,我无法访问该变量 我有这个 obj:

let human = {
  birdYear: 1,
  getAge: (function (birdYear) {
    return 2021 - this.birdYear
  })()
};

当打印人类得到这个时:

Cannot read property 'birdYear' of birdYear

我想得到这个:

{
  birdYear: 1
  getAge: 2020
}

一些手杖帮助我?我愿意使用:

  • '这个。'
  • 没有'this.birdYear'
  • (fn(birdYear){...birdYear})()
  • (fn(birdYear){...birdYear})(this.birdYear)

什么都没有

谢谢

// 添加

我是这样找到的

let human = {
  birdYear: 1,
  get getAge() {
    return new Date().getFullYear() - this.birdYear
  }
};

有效! 我只需要了解我为什么不使用 IIFE 作为方法...

【问题讨论】:

  • this 指的是你的函数,而不是它所属的对象,因为对象是对象字面量,而不是类实例。

标签: javascript object iife


【解决方案1】:

您不想创建一个可以使用内置访问器(即get)方法实例化和序列化的类吗?

class Animal {
  constructor(age) {
    this.age = age;
  }
  get birthYear() {
    return new Date().getUTCFullYear() - this.age;
  }
  serialize() {
    return { age: this.age, birthYear: this.birthYear };
  }
}

let bird = new Animal(1);

console.log(bird.serialize());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2011-10-22
    • 1970-01-01
    • 2012-06-02
    • 2013-01-17
    相关资源
    最近更新 更多