"this" is late binding. that is, it is attached to the thing immediately before the function is executed. How you call your function depends on it.
if you call it (invokation function):
myfunction();
"this" is bound to a global object
if you call it (invokation method):
myobject.myfunction();
"this" binds to "myobject"
you can also call it (invokation call):
myfunction.call(myobject);
in this case "this" is attached to myobject
exists also (constructor call):
new MyFunction();
in which "this" is bound to a newly created empty object, the prototype of which is MyFunction.prototype.
This is how javascript creators talk about it. (and I think this is discussed in the spec) Various ways of calling a function.
The new version of the ecmascript standard (ecmascript5) includes a prototype library "bind" method, which returns a new function with "this" prebound to what you specify. eg:
mynewfunction = myfunction.bind(myobject); mynewfunction();
the call to mynewfunction has "this" already associated with myobject.
Breton
source share