arrow function .this value
Hey, so i'm aware that in an arrow function,
.this
equates to the window and not the current object. If this is the case, in an arrow function, wouldn't defining a .this
value essentially be the same as defining a global variable outside of the function since they both equate to the window? If so, why would you need to utilize .this
is in a arrow function?
thanks in advance.10 Replies
that depends on how you use it
so, without seeing some code, we have to stop here
there's plenty of variations where the
this
points to many many many different thingsi don't have an example but i'll try to make one. If i do this in the arrow function, isn't it redundant since i can just have a global variable as both the
this
and global variable refer to the window?
compared to:
being an arrow function doesn't make a difference in this case
because it can be a normal one?
yes, and will work the same
now, if it was in an object, then it would be different
oh? why would it be different? because of the key value pairs?
because now it is associated to an object
normal functions'
this
changes, while arrow functions don't do thatThe value of "this" is not always the global object. It is the value of "this" of the outer scope. If there is no other "this" binding, then it becomes a reference to the global object.
Here is an example in which "this" inside an arrow function does not refer to the global object:
What happens here is nonArrow() establishes a "this" binding with its containing object, and that object has a num property. The arrow function uses the "this" of its outer scope which is the scope of nonArrow, so that "this" refers to the object that has num.
Also, the global object is not always the window object. That is only true in a browser. In the back end, it can refer to Node's globalThis or it can refer to the module object, depending on if the JS code is in a module or not.
The
call
& apply
methods of functions allow you to set this
:
Ah I see, thanks everyone