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
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With