简体   繁体   English

如何在 JavaScript 中检查变量是局部变量还是全局变量?

[英]How can I check a variable is local or global in JavaScript?

When executing a JavaScript function, how can I decide the used variable is local or global?执行 JavaScript 函数时,如何确定使用的变量是局部变量还是全局变量?

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;执行上述代码时,我只想记录a=4,而不是a=3;

<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运算符:

// 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.谨防typeof运算测试。 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 .他们只告诉你变量的值类型和返回undefined如果任一属性不存在,或者其值已被设置为未定义

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.如果变量a是原始值,则Object.is()将始终返回 true,因此您需要其他一些方法来处理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM