Possible Duplicate:
JavaScript losing “this” object reference with private/public properties
Why does the second alert shows the window object, and not the O (or even P) object?
window.name = "test window";
O = {
name : 'object O',
f : function() {
alert(this.name); // 2nd alert
}
}
P = {
name : 'object P',
f : function() {
alert(this); // 1st alert
var of = O.f;
of();
}
}
P.f();
In other words, how can a direct call to an object’s function be in the context of the window? I guess it’s a question of closure, but i have no idea where the switch happens.
Thank you.
When you do this:
Your
thisgets mangled here, becausethisisn’t really ever locked-in in JavaScript. It’s very malleable and in your case you could do a few things to make it work better.You can do any of these things to bind this properly:
or
or just