alexeypro
alexeypro

Reputation: 3673

JavaScript var visibility

Given this code:

function MyClass() {
    var v = '1';
    this.hi = function() {
        console.log('Value of V is ' + v);
        var v = '2';
        console.log('Value of V is ' + v);
        delete(v);
        console.log('Value of V is ' + v);
    }
}

When I do something like:

z = new MyClass();
z.hi();

The result I get is:

Value of V is undefined 
Value of V is 2
Value of V is 2

What I want to explain is why the result is like this.

Thanks!

Upvotes: 2

Views: 499

Answers (3)

m0sa
m0sa

Reputation: 10940

As to the why undefined part, what your code compiles to is:

function MyClass() {
    var v = '1';
    this.hi = function() {
        var v;
        console.log('Value of V is ' + v); // undefined!
        v = '2';
        console.log('Value of V is ' + v);
        delete(v);
        console.log('Value of V is ' + v);
    }
}

As you can see the var is declared at the beginning of the scope. This is how JS works. Run it through JSLint and see for yourself.

Upvotes: 1

Jamie Treworgy
Jamie Treworgy

Reputation: 24344

Change it to this:

function MyClass() {
    this.v = '1';
...

And make sure you always use this function with New.

this refers to the object that the thing is a member of. So creating this.hi makes something in a scope totally unrelated to the function itself, but using this for all members makes them all part of the same object (to which the function is assigned).

http://jsfiddle.net/hHvUq/

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385395

You can't delete a variable like that.

You can't access the v from the enclosing scope because the v in the inner scope "hides" it. Rename it.

Upvotes: 2

Related Questions