请问javascript会创建一个全局x吗?

时间:2018-05-28 23:21:46

标签: javascript function self

我想知道在这个例子中,如果x将成为一个全局变量,好像没有在本地函数中声明的那样?将javascript退出本地函数,搜索直到它找不到x,然后隐式创建一个全局x?

DB
  .push(2)
  .push(3)

1 个答案:

答案 0 :(得分:-1)

尝试运行下面的代码并注意我们如何为函数x添加()。拿出来,注意console.log中的区别。你编辑的问题有点愚蠢。只需console.log(x),看看会发生什么



var WINDOW_PROPS = Object.keys(window);



arr =[]
function f(){
    for(i = 0; i < 3; i++) {       
        arr[i] = (function(x){                               
                  return function (){
                         return x*x;
                  }();
        }(i));
        console.log(arr[i])
    }
    
    var GLOBALS = Object.keys(window)
    // filter the props which your code did not declare
    .filter(prop => WINDOW_PROPS.indexOf(prop) < 0)
    // prettify output a bit :) It's up to you...
    .map(prop => `${typeof window[prop]} ${prop} ${window[prop]}`)
    // sort by types and names to find easier what you need
    .sort();

    console.log(GLOBALS.join("\n"));

    return arr;
    
    
} 

f()
&#13;
&#13;
&#13;