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;
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;
Share Improve this question edited Oct 15, 2020 at 18:08 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Sep 26, 2013 at 22:23 user2751079user2751079 412 bronze badges 3- 1 I'm don't think you can access variables with the same name out of the scope like you want. Solution: use unique names if you need to access both. – Daniel Imms Commented Sep 26, 2013 at 22:25
-
2
window.a
should reference the global variable, but I've never done this (re-using the same variable name in different scopes) so I don't know about the potential caveats. – Jasper Commented Sep 26, 2013 at 22:26 - I want to instrument the javascript codes to only record the modification to the global variable. THe above code is just an example. – user2751079 Commented Sep 26, 2013 at 22:28
3 Answers
Reset to default 7<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?
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.
I was looking for the same thing. When I couldn't find an answer, I ended up ing 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.