I have often seen how people talk and write about this
being all complex and such. But frankly, I don’t understand the pain. All it takes for me to understand is 4-5 iterations of using this
in a different functions, classes, modules and so forth, messing up a bit - each time, and trying to do that over & over until I get the right context with the right this
.
Simple.. yet complex?
What the hell is context anyway?
Well, it is just this
. It just describes whether you are accessing a property, method or anything else of a window, of a function, class or anything else. Since almost everything is an object, this
describes the properties of the object - the value is determined through runtime binding.
This will start as an empty object.
|
|
The above code has empty object because there is no global object when you execute the code in node. But it will show window
properties when you execute the script within context of a browser window.
.. and can be anything. If you use use strict;
, this
is indeed anything. Else, it defaults to the caller or the parent - which may be the window, class etc. depending on execution.
In a function this
is determined by how the function is called.
|
|
To bind this
to anything -
|
|
You will also see that arrow functions do not bind this
context to themselves, rather they fall back on the caller.
In the context of an object, however this
is different but the same.
|
|
In the above code, this
binds to the object prop and it does not differ based on how the function is called. Also, this
can refer to the function getMake() in other contexts or continue referring to the prop make
.
this
is used with a getter or setter to refer to the object props.
|
|
The behaviour is similar in a constructor - this
is bound to the object being initiated.
Yet another piece of useless advise
Don’t get stuck on the context and how this
can be anything or nothing. Start using this
in the context of classes, objects and functions in your programs. But, do remember that this
is -
- parent object (window in browser, can be global or caller in node, definitely refers to parent object when is referred to in the a function within the object)
- refers to the object instance when used in a constructor or when used with
new <object>
- refers to self for a function, but can also refer to the parent in arrow functions where
this
is not applied to self binding - differs in behaviour when used with
use strict;
- it can be anything in that case and needs explicit binding if you want to use the power ofthis