jviotti
jviotti

Reputation: 18919

Confused about JavaScript's 'this' object and 'var' declared variables

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.

Upvotes: 1

Views: 88

Answers (1)

jfriend00
jfriend00

Reputation: 707318

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.

Upvotes: 1

Related Questions