访问全局变量的匿名函数——这怎么可能?

Anonymous function accessing global variable - how is this even possible?

当我 setInterval 设置如下时:

var intervalTime = 200;
var i = 0;
var elements = document.getElementsByTagName('elements');
var elementsLength = elements.length;

var enterElements = setInterval(function(){

    elements[i].style.transform = 'translate(0,0)';
    i++;

    if (i > (elementsLength - 1)) {
        clearInterval(enterElements);
    }

    },intervalTime);

有效!

但我认为 functions 有作用域?

我理解intervalTime应该解析正确,但是setInterval()里面的匿名函数怎么访问

我知道当我编写命名函数时,该函数无法访问在其外部声明的变量。

匿名函数与命名函数不同吗?

I know that when I write a named function, that function cannot then access variables declared outside of itself.

你怎么知道的?见 MDN:

However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function and any other variable to which the parent function has access.