I’ve learned that in function invocation, this would refer to the global object. In the function below, which is the global object?
Is it the Function or there’s a single default global object where this would refer to? In addition to that, what does this code actually do? I am particularly confused about the method placeholder. Does it have to be replaced with a method that’s pre-existing in Function.prototype?
And in the line this.prototype[name] = func;, which property is it referring to, the method’s or the Function.prototype’s?
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
The
thiskeyword refers to the current object, and if the scope of a function is the global namespace, the current object is the global object, i.e. thewindowobject if the environment is a browser.As you are adding a method to the
Functionclass, thethiskeyword will refer to the function that you are calling themethodmethod on, so it will return the function itself so that the calls can be chained.This will declare the function
Fas a constructor, create an object of the typeF, add the functionxas a method toFand name itxx, then use the objectfto callxxwhich really isx:So, this:
is the same as: