“未捕获reference"在ES6类中使用“for of”方法时出现错误

"Uncaught reference" error in ES6 class when using `for of` in method

本文关键字:of for 方法 错误 未捕获 reference quot ES6      更新时间:2023-09-26

我试图使用for of在我的一个方法以下ES6语法和运行到Uncaught ReferenceError: item is not defined.消息是明显的,我已经修复了它。

我的问题是,为什么我们必须显式声明变量时,使用它在方法中循环,而不是在全局作用域?为什么我们在全局作用域中隐式声明的变量可以在之后的类中使用?

的例子:

var arr = ["a", "b", "c", "d"];
for(i of arr){
  console.log(i);
}
    class bar{
        constructor(arr){
            this.innerArr = arr;
        }
      // so how this one gets reference to outside i?
        yell(){
            for(i of this.innerArr){
                console.log(i);
            }
        } 
    }
    class baz extends bar{
      // in here it's obviously fine because we have var ii
        yell(){
            let ii
            for(ii of this.innerArr){
                console.log(ii);
            }
        } 
    }
    class foo extends bar{
      // This gives Uncaught ReferenceError
        yell(){
            for(item of this.innerArr){
                console.log(item);
            }
        } 
    }
    var br = new bar(arr);
    var bz = new baz(arr);
    var f = new foo(arr);
    br.yell();
    bz.yell();
    f.yell();

只是感觉有点违反直觉。

问题与for of无关。ECMAScript规范声明

ClassDeclaration或ClassExpression的所有部分都是严格模式代码。

在严格模式下,您不能访问尚未声明的变量。

至于为什么bar.yell()可以访问i: i已经被声明为全局变量,因为这段代码:

for(i of arr){
  console.log(i);
}

该代码以非严格模式在全局作用域中运行。因为i被自动声明为全局变量

如果要在局部范围内使用该变量,则必须使用let关键字。请参阅https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/let

var关键字可以在全局和局部范围内使用和覆盖。我想这是因为JavaScript的历史