tags:

views:

42

answers:

1

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;
    };
+1  A: 

The this keyword 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. the window object if the environment is a browser.

As you are adding a method to the Function class, the this keyword will refer to the function that you are calling the method method on, so it will return the function itself so that the calls can be chained.

This will declare the function F as a constructor, create an object of the type F, add the function x as a method to F and name it xx, then use the object f to call xx which really is x:

function F() {}
function x() { alert(1); }

var f = new (F);
F.method('xx', x);
f.xx();

So, this:

F.method('xx', x).method('yy', y);

is the same as:

F.prototype.xx = x;
F.prototype.yy = y;
Guffa
so the "method" part in Function.prototype.method is actually a reserved keyword? Is that right? And the code as a whole just simply assigns a method x to xx?
Joann
@Joann: No, `method` is not a reserved keyword, it's just a name for a method. Yes, the code is just for adding methods to a class.
Guffa