Saturday, October 24, 2020

What does 'this' keyword in Javascript

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. 


ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).


A property of an execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.


Global context

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.


Function context

Inside a function, the value of this depends on how the function is called.


Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.


Class context

The behavior of this in classes and functions is similar, since classes are functions under the hood. But there are some differences and caveats.


Derived classes

Unlike base class constructors, derived constructors have no initial this binding. Calling  super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where Base is the inherited class:





References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

No comments:

Post a Comment