Manngo
Manngo

Reputation: 16291

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

Upvotes: 4

Views: 586

Answers (3)

Pyrogrammer
Pyrogrammer

Reputation: 183

I pulled this from scope and modify so that you can learn a bit more tricks. Check this example out.

<!DOCTYPE html>
<html>
<body>

<p>
In HTML, all global variables will become window variables.
</p>

<p id="demo"></p>

<script>
var apple=3;
var obj=new thing();
document.getElementById("demo").innerHTML =
"I can display " + window.apple + " and " + window.banana + " but not local " + window.orange + ". I can call this from getter though " + obj.getOrange();


function thing() {
    banana=4;
    var orange=5;

    this.getOrange = function(){
        return orange;
    }

}
</script>

</body>
</html>

Output will look like this.

In HTML, all global variables will become window variables.

I can display 3 and 4 but not local undefined. I can call this from getter though 5

So unless you create the getter and setter for local variables, you will not be able to reference them. Global cariables will become window varaibles.

Upvotes: 0

Andrew Dunai
Andrew Dunai

Reputation: 3129

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

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816442

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?

Upvotes: 7

Related Questions