Reputation: 41
When executing a JavaScript function, how can I decide the used variable is local or global?
Because I only want to record the modification to the global variable.
<script>
var a;
a =4;
function foo(){
var a =3;
}()
</script>
when executing the above code, I only want to record the a=4, not a=3;
Upvotes: 4
Views: 1761
Reputation: 121
I was looking for the same thing. When I couldn't find an answer, I ended up coming up with this:
<script>
var a;
a = {prop1: 'global object'};
(function foo() {
var a = {prop1: 'local object'};
var isLocal = true;
if (window.hasOwnProperty('a')) {
if(Object.is(a, window['a'])) {
isLocal = false;
}
}
})();
</script>
If variable a
is a primitive value, then Object.is()
will always return true, so you'd need some other way to deal with them.
Upvotes: 0
Reputation: 101604
<script>
var a;
a = 4;
function foo(){
// version 1:
if (window.hasOwnProperty('a')){
// "global" a exists
}
// version 2:
if (typeof window.a !== 'undefined'){
// "global" a exists and is defined
}
}();
</script>
Something like that?
Upvotes: 7
Reputation: 147393
Global variables are added as properties of the global object, which is window in a browser. To test if an object has a property or not, use the in
operator:
// In global scope
var bar;
function foo() {
if (bar in window) {
// bar is a property of window
} else {
// bar isn't a property of window
}
}
For more general code, the environment may not have a window object, so:
// In global scope
var global = this;
function foo() {
if (bar in global) {
// bar is a property of the global object
} else {
// bar isn't a property of the global object
}
}
Beware of typeof tests. They only tell you the type of the variable's value and return undefined if either the property doesn't exist or its value has been set to undefined.
Upvotes: 3