“未捕获reference"在ES6类中使用“for of”方法时出现错误
"Uncaught reference" error in ES6 class when using `for of` in method
我试图使用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的历史
相关文章:
- 使用for.of迭代时删除集合中的元素是否安全
- Mock window.document object for out-of-browser jQuery
- 如何做承诺.all for array of promises.
- 如何更改 for-of 循环中的元素
- Javascript setter for value of object
- Tree for ChildNode of childNode in JavaScript
- 为什么for.of不记录foo值
- Colspan & rowspan of header for slickgrid
- 为什么在 for.of 循环中具有两个变量名称的示例代码不起作用
- for-in and in of JS
- Alternative for "for of"-loop
- Some kind of JavaScript's preventDefault for Android
- 如何在for of循环中访问i的当前编号
- 如何使for of循环向下迭代,而不是通过数组向上迭代
- JavaScript for ... of loop
- “未捕获reference"在ES6类中使用“for of”方法时出现错误
- TypeScript编译器无法在for of循环中找到immutable.js Map迭代器
- 用for…of来理解解构
- SyntaxError:带有for的意外标识符.nodejs中的Of循环
- ES6中的多个for-of循环定义