Why do I lose the context of this in Javascript?
If you do it like as follows,
function will be called in o2 context
var o2 = {
a: 11,
b: 22,
f2: function (j){
this.temp = j;
this.temp();
}
};
also these will work too:
f2: function (j){
j.apply(this);
}
f2: function (j){
j.apply(o2);
}
Otherwise you call it just like an ordinary function out of context.
j Is ripped out of its context and you did no tricky closures on it(which is not your intent) so for making "this" work in it you need a scope. The this scope in your question for j is window, which has no "b" in it therefore you get an "undefined".
I found Crockford had an excellent description of the way this works. Functions in JavaScript can be invoked in 4 styles :
- The "function" style
- The "method" style
- The "Constructor" style
- The "call or apply" style.
I might be getting the exact names wrong there, but the spirit is the same. You should definitely get the book "JavaScript: The Good Parts" if you don't have it.
So anyway - on to your question. The key thing is that the value if "this" is dependant on which style you use.
// function invocation style,
var f = function() { console.debug(this); }
f(); // "this" is bound to the global object.
// "method" invocation style
var obj = {
f: function() { console.debug(this); }
};
obj.f(); // "this" is bound to "obj", the object on which the function was invoked
// so important bit is :
var f = obj.f;
f(); // "this" is global object
obj.f() // "this" is obj
In your example you are losing "this" because of the way you are invoking the function.