In the MDN Docs,
When a static or prototype method is called without a value for this
, such as by assigning the method to a variable and then calling it, the this
value will be undefined inside the method.
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
const obj = new Animal();
obj.speak(); // the Animal object
const speak = obj.speak;
speak(); // undefined
Animal.eat() // class Animal
const eat = Animal.eat;
eat(); // undefined
I dont understand that when we save a normal/static method reference to a variable, why do we lose the reference of this
?
Also speak() is like a normal class method. Is this method said to be a prototype method in the text above?
As a solution, it is written:
If we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls are automatically bound to the initial this value, which by default is the global object. In strict mode, autobinding will not happen; the value of
this
remains as passed.
And the code provided as a solution:
function Animal() { }
Animal.prototype.speak = function () {
return this;
}
Animal.eat = function () {
return this;
}
const obj = new Animal();
const speak = obj.speak;
speak(); // global object (in non–strict mode)
const eat = Animal.eat;
eat(); // global object (in non-strict mode)
“ then this method calls are automatically bound to the initial this value, which by default is the global object.” - in which line does the this method call take place?
Link : MDN Docs link