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?
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