Sobes.tech
Junior — Senior

How does this work in class methods and regular objects

livecode

Task condition

It is necessary to predict what will appear in the console when calling the methods say and say2 on an instance of the class and on a simple object. Consider the differences between arrow functions and regular functions.

class Animal {
  sound = 'meow';
  say = () => {
    console.log(this.sound);
  };
  say2() {
    console.log(this.sound);
  }
}

const objCat = {
  sound: 'meow',
  say: () => {
    console.log(this.sound);
  },
  say2: function () {
    console.log(this.sound);
  }
}

const catObj = new Animal();
catObj.say();     // ?
catObj.say2();    // ?
objCat.say();   // ?
objCat.say2();  // ?