The referece of this
depends on how you are calling the function.
For example:
function globalFn() { return this.val; }
var objectA = { val: 1, localFn: globalFn };
var objectB = { val: 2, localFn: globalFn };
objectA.localFn(); // `this` will be `objectA`, so it returns `1`.
objectB.localFn(); // `this` will be `objectB`, so it returns `2`.
So far, so good. It looks like the same as in Java or other object oriented languages. But, this may seem tricky:
var myFn = objectA.localFn;
myFn(); // `this` will be `undefined` in strict mode, causing an error
This shows that this
reference is not bound to the function itself, but to the way the function is called. You can "cheat" it by using call
method of a function object:
myFn.call(objectA); // `this` will be `objectA`, returns `1`.
globalFn.call(objectB); // `this` will be `objectB`, returns `2`.
objectA.localFn.call(objectB); // `this` will be `objectB`, returns `2`.
You can even do this for objects that does not have the function defined as a property:
var objectC = {val: 3};
myFn.call(objectC); // `this` will be `objectC` and will return `3`.
It's quite hard to understand it at first, there's a great video that illustrates how it works at YouTube: The Definitive Guide to Object-Oriented JavaScript by James Shore.