Javascript variable has different value in anonymous callback -


i came across bug , didn't find example anywhere. documenting here reference.

the problem when calling o.callback() in example below, value of x changes between defining , executing 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 expected:

o.f() local 

update here's jsfiddle: http://jsfiddle.net/elplatt/kzs5a/1/

the variable "x" global, because it's not declared explicitly var. of functions reference same "x".

object properties in javascript must explicitly referenced such. is, unlike languages c++ or java, javascript provides no implicit references "member variables". if want property "x" on objects, you'll have refer this.x.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -