0

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/

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That would give the desired output in this example. It's a slightly different behavior from what I intended. this.x would always refer to o.x while var x would be a different variable each time o.f() gets called.
0

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.

4 Comments

That will change things, but now that callback function will have access to neither of those variables.
Not true, that confuses scope with context. Using var makes x within the local scope refer to x in the global context (window). Using this.x refers to x within the context of whatever object "this" is.
That is incorrect. A var declaration inside a function creates a variable that is local to that function.
Sorry, I meant to say not using var makes x within the local scope refer to x in the global context. You are correct that using var x creates a variable local to that function (with no context).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.