If you have spent some time reading or writing JavaScript, you will have no doubt came across the this
keyword. In other object orientated languages, the this
keyword refers to the current instance of the class. In JavaScript the value of this depends on the context of the function and where it is called.Not knowing this or rather this
can be confusing.
JavaScript functions get two arguments passed silently arguments
and this
, the second being the more widely used of these implicit arguments.
In this post I'm going to be looking at this
in four different situations:
- In a regular function.
- When a function is called as a method.
- In a function that's being called as a constructor.
- When you explicitly set the value of
this
manually usingbind
,apply
, orcall
.
Let's get started...
In a regular function
In a regular function ( or anywhere outside of a function ) when in non strict modethis
refers to the window object, or the root of the DOM. In strict mode i.e.. when "use strict";
is at the top of the JavaScript file, this
is undefined, which is probably more desirable and will reduce any unwanted side effects.
When a function is called as a method
this
inside of an object refers to the object on which the method is being called on. In the above example this refers to the anObject..object. Gordon Zhu founder of Watch and Code, uses the term "the left of the dot rule", which I think is a great way to identifying what this
will refer to.
For example if we had something that looked like object.innerObject.oneMoreObj.doSomething()
using the "left of the dot rule", We can quickly see that doSomething is a method of the oneMoreObj object.
In a function that's being called as a constructor
In a function that's being used as a constructor, this
points object that has been created from the constructor.
When you explicitly set the value of this
manually using bind
, apply
, or call
.
Bind sets the 'this' of the function, call and apply execute the function and set the this
. Call and apply are very similar except apply takes arguments as an array and call takes its arguments as a comma separated list. I look at the first letter to remember the difference, apply: array, call: commas. It is worth noting once bind is set, it is bound once and cannot be changed.
The most important thing to remember when trying to figure out what this
equals is the context in which the function is being called.
That was this
.
Thanks for reading!
Some additional resources:
Just ran over that today, when I got back to coding a bit in javascript after a while of absence =D
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Good post Adam. I learned a lot from Watch and Code: Practical JavaScript. Good to see you mention it here.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit