This
What the fuck is this?!
How
this
value for a function is determined by how the function are called.
Objects
In the example below this
will point to globalThis, In browser globalThis is window
and in node globalThis is global
This is proper way to do it
So now you can borrow a function reference.
There is another way to use function from antoher object. You can use keyword new
.
new
keyword hijacks a function and forces its behavior into a different mode than a normal invocation. Here are the 4 special steps that JS performs when a function is invoked with new:
- create a brand new empty object, out of thin air.
- link the
[[Prototype]]
of that new empty object to the function's .prototype object - invoke the function with the
this
context set to that new empty object. - if the function doesn't return its own object value explicitly (with a return .. statement), assume the function call should instead return the new object
Step 4 implies that if you new invoke a function that does return its own object, like return { .. }
, etc, then the new object from steps 1-3 is not returned.
There are four rules for this
context assignment in function calls:
- Is the function invoked with
new
, creating and setting a newthis
? - Is the function invoked with
call(..)
orapply(..)
, explicitly settingthis
? - Is the function invoked with an object reference at the call-site (e.g.,
point.init(..)
), implicitly settingthis
? - If none of the above... are we in non-strict mode? If so, default the
this
toglobalThis
. But if in strict-mode, default thethis
toundefined
.
These rules, in this order, are how JS determines the this
for a function invocation. If multiple rules match a call-site (e.g., new point.init.call(..)
), the first rule from the list to match wins.
Arrow functions
Arrow functions differ in their handling of this: they inherit this from the parent scope at the time they are defined. This behavior makes arrow functions particularly useful for callbacks and preserving context. However, arrow functions do not have their own this binding. Therefore, their this value cannot be set by bind(), apply() or call() methods, nor does it point to the current object in object methods.
If you wish to learn more about this
subject, follow these links:
https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/objects-classes/ch4.md