DEV Community

Discussion on: Day 8 : Learning JS fundamentals, Part -3

Collapse
 
marzelin profile image
Marc Ziel

It is all about the call, it is not the definition of the function, it is not where the function is, none of that matters, it is only how the function was called that determines where the this keyword will be pointing to.

This isn't entirely true. You can bind a function and that sets this at creation time. Only new operator can change what this refers to on a binded function at call time.

Collapse
 
gauravshekhawat profile image
Gaurav-Shekhawat

Can you please elaborate, I am not able to understand. A link or something regarding the same will suffice.

Collapse
 
marzelin profile image
Marc Ziel

If you bind a function:

const bound = function () {
   console.log(this);
}.bind({type: "bound"});
Enter fullscreen mode Exit fullscreen mode

then no matter how you call the function (except new).
You can use .:

const o = { bound, type: "dot notation" };
o.bound();
Enter fullscreen mode Exit fullscreen mode

apply or call:

bound.call({type: "call"});
Enter fullscreen mode Exit fullscreen mode

or even call it directly:

bound();
Enter fullscreen mode Exit fullscreen mode

but this will always be the bound object: {type: "bound"}.

Thread Thread
 
gauravshekhawat profile image
Gaurav-Shekhawat

thank you so much for your assistance