"this" is late binding. that is, it gets bound to a thing just before the function is executed. What it is bound to depends on how you call your function.
if you call it like (function invokation):
myfunction();
"this" is bound to the global object
if you call it like (method invokation):
myobject.myfunction();
"this" gets bound to "myobject"
you can also call it like so (call invokation):
myfunction.call(myobject);
in which case "this" gets bound to myobject
there is also (constructor invokation):
new MyFunction();
in which "this" gets bound to a newly constructed blank object whose prototype is MyFunction.prototype.
this is how the creators of javascript talk about it, anyway. (and I think it is discussed this way in the spec) Different ways of invoking a function.
the new version of the ecmascript standard (ecmascript5) includes the prototype library's "bind" method, which returns a new function with "this" prebound to something you specify. for instance:
mynewfunction = myfunction.bind(myobject);
mynewfunction();
the invokation of mynewfunction has "this" already bound to myobject.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…