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:
var of = O.f;
of();
Your this gets mangled here, because this isn'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:
var of = O.f.bind(this);
of();
or
var of = O.f
of.call(this);
or just
O.f.call(this);
If you want to maintain scope of O then try this
window.name = "test window";
O = {
name : 'object O',
f : function() {
alert(this.name); // 2nd alert
}
}
P = {
name : 'object P',
f : function() {
alert(this.name); // 1st alert
var of = O.f;
of(); // loses scope since this.of does not exist it calls using anonymous window scope
of.call(O); // passes O as scope
of.call(P); // passes P as scope
this.of = O.f;
this.of(); // maintains current P scope
}
}
P.f();
Here's a fiddle: http://jsfiddle.net/QVSDA/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With