Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Variables vs Properties

In JavaScript a global variable is also a property of the window object. What about local variables? Are they the property of any object?

For example:

var apple=3;
alert(apple);                   //  3
alert(window.apple);            //  same

thing();

function thing() {
    var banana=4;
    alert(banana);              //  4
    alert(thing.banana);        //  doesn’t work, of course
}

Is banana a property of any object

like image 269
Manngo Avatar asked Jan 08 '23 14:01

Manngo


2 Answers

What about local variables? Are they the property of any object?

No. When execution enters a function, a new declarative environment record is created for storing the identifiers.

Unlike object environment records (used for creating the global and with environments) there is no user space object to which the variables are mapped.

See also What really is a declarative environment record and how does it differ from an activation object?

like image 68
Felix Kling Avatar answered Jan 18 '23 14:01

Felix Kling


But you can still store stuff inside function object. This way you can have something called static variable in languages like C/C++. For example:

function thing() {
    thing.banana = (thing.banana + 1) || 1;
    alert('This function was ran '+ thing.banana + ' times.');
}

thing(); // alerts "This function was ran 1 times"
thing(); // alerts "This function was ran 2 times"
thing(); // alerts "This function was ran 3 times"
thing(); // alerts "This function was ran 4 times"
thing(); // alerts "This function was ran 5 times"
alert(thing.banana) // alerts 5
like image 35
Andrew Dunai Avatar answered Jan 18 '23 14:01

Andrew Dunai