This is fixed by using var
to define x
var x = 'o.f() local'
The x
in both o.f
and p.f
was in global scope because it was never declared with var
.
Domanda
I came across this bug and didn't find an example anywhere. Documenting here for reference.
The problem was that when calling o.callback()
in the example below, the value of x
changes between defining and executing the callback.
p = {
f: function () { x = 'p.f() local'; }
};
o = {
f: function () {
x = 'o.f() local';
this.callback = function () { console.log(x); };
}
};
o.f();
p.f();
o.callback.apply();
The output here is:
p.f() local
While I expected:
o.f() local
Update Here's a jsfiddle: http://jsfiddle.net/elplatt/kzS5A/1/
Soluzione 2
This is fixed by using var
to define x
var x = 'o.f() local'
The x
in both o.f
and p.f
was in global scope because it was never declared with var
.
Altri suggerimenti
The variable "x" is global, because it's not declared explicitly with var
. Thus all of those functions reference the same "x".
Object properties in JavaScript must always be explicitly referenced as such. That is, unlike languages like C++ or Java, JavaScript provides for no implicit references to "member variables". If you want a property "x" on those objects, you'll have to refer to it as this.x
.