Given the following snippet copied from a well known question on this site:
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
My logic to understand this is:
- Since the (first)
getX
belongs to themodule
object, it cannot be seen without the prefixmodule.
, so everyone knows that it should bemodule.getX()
- But what causes confusion is that
this
of the (first)getX
will also reference the pointer calling the (first)getX
function. I'm not sure about whether my wording is correct. - When I define the second (pointer to) function by
var getX = module.getX
, it helps us to keep seeing the firstgetX
inside/ofmodule
.
But, since most people (in the past) didn't know about the second point, i.e. the pointer used when calling the function matters, i.e.
// the second getX() in the above example.
getX()
// is equivalent to:
globalPointer.getX()
and since the global x = 9
is belongs to the globalPointer
, so the result is 9
instead fo 81
.
Please help me check about my understanding, either the correct wording or the real logic behind the scene are welcome.