What is ‘this’ referring to in JavaScript
If you are not aware of how you are using the keyword ‘this’ inside the scope context. this can give you tons of errors and headache.
So let us have a look at some examples of what this is and how we can control it.
Executing this inside our console would return the global Object Window.
Lets create a Object called world with a method called display that returns this.
As we can see this is no longer referring to the global Window Object, it’s now referring to the enclosing execution context which is the world Object.
So now that we know when this is this lets have a look on a more practical example.
We can cache this from its surrounding environment and then pass it down the scope chain.
Lets create an array in the global Object, declare that and assign it to this.
Introducing function.prototype.bind() and .call()
We can bind this inside our display method to reference the global Window Object. Like this.
Lets declare a variable and assign it to the display method.
foo dont know display methods original surrounding context and refer this to the global Window Object instead of world.
We can provide the original scope for this, by using the .call() method.
With Arrow functions in ES6 this is set lexically
This has been a brief introduction to this and its scope references. Can be good to know that working in strict mode or sloppy mode can change this behavior.
I hope you found this article helpful and feel free to comment below.
Enjoy your code.