Short answer:
You can set this to a function using the .call() and .apply() methods.
Long answer:
The this variable for any function is similar to the arguments variable (probably this is something you did not know about). It is set when the function is called and is an artifact of how the function is called. To explain, let me start by demonstrating the arguments . Consider:
myFunction = function () { return arguments.length; };
Now look at a couple of myFunction calls:
myFunction(); //is 0 myFunction(null); //is 1 myFunction(undefined); //is 1 myFunction(0, 0, 0, 0, 0); //is 5
As you can see, the value of arguments.length does not depend on how and where we wrote the function, but how we called this function. The same applies to the this variable (otherwise called the "caller"). There are only 3 methods for setting the caller (there is a 4th one in ES5, but we will ignore it):
- You can set it by calling the function using dot notation (e.g.
something.myFunction() ) - You can set it using
.call() or .apply() methods (e.g. myFunction.call(someObject) ) - If it is not installed using method # 1 or # 2, it will be the default global object (e.g.
window )
Thus, most people use method # 1. If you assign your function as a property of an object, then call the function using the object and dot notation, then the object gets the value this . For example:
var myFn = (function () { return this.x }); var myObj = { x: 1, y: myFn }; myObj.myFn();
But we can also use method 2 if myFn not a property of the object we want to call it, but the object follows the correct form for myFn to be able to work on it (see: duck typing):
var myOtherObj = { x: 2 } myFn.call(myOtherObj); //is 2 myFn.apply(myOtherObj); //is 2 myFn.apply({ x : 3}); //is 3
Pretty cool, huh? Here's how jQuery does it. When they make your callback, they do it with .apply(event.target) (setting this for the event target). They do this in a more complicated way because of their callbacks framework, but the idea is there .
In any case, I would not offer a long answer if I did not throw an explanation of method No. 3, which keeps some people crazy: what happens if you do not install the calling object?
Since all global variables are implicit properties of a global object, you get some interesting effects from method # 3. For example:
var x = 4; myFn();
But most of the time you are out of luck if your global object meets the requirements of the function for the calling object, so this usually leads to an error and a lot of frustration.
Probably more than you were looking for, but hopefully you are now much more informed about the caller and its tricky ways.