In the following example I have a class and add two functions by prototype , the first one as defined funcion normalmente
, while the second one witharrow function
simpleClase = function(){
this.ejemplo = 1
}
simpleClase.prototype.simple = function(){
console.log(this)
}
simpleClase.prototype.arrow = () =>{
console.log(this)
}
let nuevaClase = new simpleClase();
nuevaClase.simple();
nuevaClase.arrow();
The case is that for the function as normally defined with prototype it returns me the contexto de la clase
, while using arrow function
it returns mewindow
With another Example:
class Clase {
constructor(){
this.valor = 1
}
arrow() {
let miFuncion= () => console.log("arrow" , this);
miFuncion();
}
simple(){
console.log("simple" , this);
}
}
let miClase = new Clase();
miClase.arrow()
miClase.simple()
It returns the context of the class, this gives me the doubt of how prototype works with the arrow function , my doubt is because these scopes are different, because the prototype does not take the scope of the variable
TL;DR:
is almost 1 equivalent to
Explanation with more examples:
Let's see how the arrow function works and how it defines its context. But first let's look at a normal function and its behavior:
The context of the function varies depending on how it is called.
This could be avoided with the Function class's bind method:
Well, an arrow function is the equivalent of using .bind(this) at declaration time:
Using classical notation to create a class:
As you can see, a classic function receives the context at runtime, whatever it is called.
Using the arrow function
1 Arrow functions do not have the implicit variable
arguments
that other functions have. It's not exactly the same.It's not that the arrow functions don't have access to the
this
. If they do, only that they have access to the scope that surrounds them or the parent scope. The documentation says:Imagine that inside a class, you define a private class, for whatever reason. Now, in the private class you have a function
prototype
defined in the form of an arrow and from that function you need to access the properties of its own instance:Note how
corazon.latir()
instead of printing 4, it showsundefined
and in thethis
shows the definition of person. This is because itthis
provides access to the parent (enclosing) scope, which would bePersona
.In your case, when you define a class in the global scope and create an instance of it, the parent scope of that instance is
Window
, not the object instance. As in the case of the example, the parent (enclosing) scopeprototype
of the private classCorazon
, isPersona
.Let's look at the scopes as a box. this in arrow functions provides access to the scope that surrounds them and since
this
it is inCorazon
, it would only give access toPersona
, not window, since itCorazon
is insidePersona
:But in your case, it would navigate to window since it doesn't have another scope that wraps it: