2

In below example, I tried calling Animal Class's methods speak() and eat() in 4 different ways, and they returned different results:

Here is the example:

class Animal { 
  speak() {
    console.log(this);
    return this;
  }
  static eat() {
    console.log(this);
    return this;
  }
}

//scenario #1
let obj = new Animal();
obj.speak(); // Animal {}

//scenario #2
let speak = obj.speak;
speak(); // undefined

//scenario #3
Animal.eat() // class Animal

//scenario #4
let eat = Animal.eat;
eat(); // undefined

Can someone please explain why there are different results when we called the same methods (speak() and eat()) in these 4 scenarios?

Output: Output

Scenario #1: Prints: {}

let obj = new Animal();
obj.speak(); // Prints: {}

Scenario #2: Prints: undefined

let speak = obj.speak;
speak(); // Prints: undefined

Scenario #3: prints: Class definition of Animal Class

Animal.eat() // prints: Class definition of Animal Class

Scenario #4: Prints: undefined

let eat = Animal.eat;
eat(); // Prints: undefined
Aaditya Sharma
  • 2,125
  • 1
  • 19
  • 34
  • Please feel free to suggest/edit a better title for this question (for the benefit of this SO community). – Aaditya Sharma Aug 19 '19 at 09:37
  • 1
    I keep an up to date answer explaining how `this` works in all situations. I will keep updating it as the standard evolves: https://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Aug 19 '19 at 09:59
  • [Understand JavaScript `this` keyword](https://www.zeolearn.com/magazine/understanding-the-this-keyword-in-javascript) – Florian Aug 19 '19 at 10:02

1 Answers1

1

One important aspect of Javascript is how this works.

When you execute

 x.foo()

what happens is that right before entering the code of foo the special value this is set to the object x. Writing for example:

 let f = x.foo;
 f();

is NOT the same, because here this will be set to the global object when entering the code of foo.

6502
  • 104,192
  • 14
  • 145
  • 251