1

I'm a bit confused about JavaScript's this object.

var contextTest = function() { var x = 0; } var test = new contextTest; console.log(test.x); // produces undefined 

What's the difference between the above and this.x = 0; inside the function?

I always thought that declaring a variable like that will bind the variable to the scope.

4
  • 6
    var x = 0 does not assign the variable to the function. It merely happens to live inside it Commented Jan 25, 2013 at 17:34
  • 3
    read this all night long Commented Jan 25, 2013 at 17:34
  • 1
    @NikolaNinkovic upvote just for the text, i didn't even look at the page. Commented Jan 25, 2013 at 18:08
  • @jbabey thats just the way it is :) Commented Jan 25, 2013 at 23:22

1 Answer 1

1

Declaring:

var x = 0; 

just creates a local variable in whatever function scope you're in.

That variable exists only for the lifetime of that function or function closure. This type of declaration NEVER binds this variable to an object as a property. To do that, you must explicitly assign a value to a property of the object as in this.x = 0;.

If you use a construct that causes the function closure to persist (which you have in your code), then the value of the local variable will exist in the function closure as a privately accessible variable, accessible only from that particular function in that particular context. It will behave in some ways like a private instance variable of your object. But, it is NOT a property of the object and you cannot reference it via this or any other reference to the object. You can only reference it from the function in which it is declared.

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

2 Comments

why repeat what they said?
@Ark - I'm not sure what your comment means. I provided an answer to the question and offered significantly more info than any other comment had provided. There were no other answers that provided this info.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.