zjmiller
zjmiller

Reputation: 2787

When I declare a variable inside a function, which object is it a property of?

So when I declare a variable outside the scope of any function, it becomes a property of the window object. But what about when I declare a variable inside the scope of a function? For example, in the following code I can treat x as a property of window, i.e., window.x, but what about y? Is it ever the property of an object?

var x = "asdf1";

function test() {
var y = "asdf2";
}

test();

Upvotes: 1

Views: 5357

Answers (3)

a.stgeorge
a.stgeorge

Reputation: 304

In order to declare a JS variable a property of an object you need to either use the new Object(); method or the {} syntax.

var variableName = new Object();
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc};

Then you can assign child objects or properties to said variable object

variableName.aPropertyNameIMadeUp = 'hello';
variableName.aChildObjectNameIMadeUp = new Object();

As such the new variable object is associated with a method if it is within the method call.

Cheers

Upvotes: 0

Manish Trivedi
Manish Trivedi

Reputation: 3559

See following example (I have copy from other question-answer) very nice:

// a globally-scoped variable
var a=1;

// global scope
function one(){
    alert(a); 
}

// local scope
function two(a){
    alert(a);
}

// local scope again
function three(){
  var a = 3;
  alert(a);
}

// Intermediate: no such thing as block scope in javascript
function four(){
    if(true){
        var a=4;
    }

    alert(a); // alerts '4', not the global value of '1'
}


// Intermediate: object properties
function Five(){
    this.a = 5;
}


// Advanced: closure
var six = function(){
    var foo = 6;

    return function(){
        // javascript "closure" means I have access to foo in here, 
        // because it is defined in the function in which I was defined.
        alert(foo);
    }
}()


// Advanced: prototype-based scope resolution
function Seven(){
  this.a = 7;
}

// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.



// These will print 1-8
one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);

Upvotes: -1

Ian Clelland
Ian Clelland

Reputation: 44152

It becomes a property of the Variable object associated with the function call. In practice, this is the same thing as the function call's Activation object.

I don't believe that the Variable object is accessible to running JavaScript code, though; it's more of an implementation detail than something you can take advantage of.

Access all local variables is a related question here on SO.

Upvotes: 4

Related Questions