Generally 'this' is pointing to the object hosting the method called. (You may override this by function.call(thisObject, arg1, arg2) or function.apply(thisObject, [argList]).)
A simple example:
var myObject = {
value: 1,
report: function() {
return "value: " + this.value;
}
}
console.log( myObject.report() ); // "value: 1"
Should be quite clear.
Using a constructor and a prototype, it would be:
function Reporter(v) {
this.value = v;
}
Reporter.prototype = {
report: function() { return "value: " + this.value; }
};
var myObject = new Reporter(1);
console.log( myObject.report() ); // "value: 1"
Works just the same. 'this' is the object created by calling "new Reporter(1)" and the 'this' in the prototype is referring to the object which's method "report()" is called.
(The prototype comes only into play, if there's no method "report()" defined in the "myObject" as an own property.)
Now a bit more nested:
function ComplexReporter(v) {
this.value = v;
}
ComplexReporter.prototype = {
report: function() { return "value: " + this.value; },
utils: {
innerReport: function() { return "value: " + this.value; }
}
};
var myObject = new ComplexReporter(1);
console.log( myObject.report() ); // "value: 1"
console.log( myObject.utils.innerReport() ); // "value: undefined"
The first call is just as above and provides the expected result.
In the second call, 'this' is not as might be expected 'myObject', but 'myObject.prototype.utils', which has no property @value of any kind.
This is effectively
ComplexReporter.prototype.utils.innerReport.apply( myObject.prototype.utils, [] );
So as a rule of thumb, 'this' is the entity described by the path to the very last identifier before the last dot when invoking an object's method in dot-notation.
The last example without the prototype (to make it a bit simpler again):
var myComplexObject = {
value: 1,
report: function() {
return "value: " + this.value;
},
utils: {
innerReport: function() {
return "value: " + this.value;
}
}
}
console.log( myComplexObject.report() ); // "value: 1"
console.log( myComplexObject.utils.innerReport() ); // "value: undefined"
// same as myComplexObject.utils.innerReport.apply( myComplexObject.utils, [] );
console.log( myComplexObject.utils.innerReport.apply( myComplexObject, [] ) ); // "value: 1"
And: 'this' is always evaluated the very moment, the function is called (so you can't save the contextual meaning of 'this' when constructing a closure).
I hope, these examples helped a bit in understanding how 'this' works ...
P.S.: If the this-object provided with a call to function.call() or function.apply() is undefined or null, the global object ('self', in a browser identical to 'window') is used as 'this'.