-2

when i want that the property get year to print, i cant acces to the variable I have this obj:

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

when print human get this:

Cannot read property 'birdYear' of birdYear

and i want get this:

{
  birdYear: 1
  getAge: 2020
}

some cane help me? I thy with using:

  • 'this.'
  • without 'this.birdYear'
  • (fn(birdYear){...birdYear})()
  • (fn(birdYear){...birdYear})(this.birdYear)

and nothing

THANKS

// ADD

i found this way

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

Works! I only need to understand why not I use IIFE as methods...

Nube Nube
  • 47
  • 5
  • 1
    `this` refers to your function, not to the object it belongs, because the object is an object literal, not a class instance. – r3wt Jan 08 '21 at 16:27

1 Answers1

1

Wouldn't you want to create a class that you can instantiate and serialize with a built-in accessor (i.e. get) method?

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());
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132