Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - Block scoping of let and for…of

The let statement in ES2015 allows us to declare block scope variables, so that for example the following code does what we want:

let fs = [];
for (let i = 0; i < 3; i++) {
    fs.push(() => i);
}
console.log(fs.map(f => f())); // 0, 1, 2

However, it does not seem to work in Firefox with the for…of loop which iterates over iterable objects. Here, the block scope is ignored, and we get the same result as if we used var instead:

fs = [];
let nums = [0, 1, 2];
for (let i of nums) {
    fs.push(() => i);
}
console.log(fs.map(f => f())); // 2, 2, 2

Why is the behavior of let not working here, and what’s internally so different about the for…of loop that this breaks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As others pointed out in the comments, this broken behavior seems to be specific to Firefox, and the code is working properly in other environments (e.g. V8/Node).

As such, I have created a bug report for it. I’ll update this answer as I learn something new from the Firefox team.


This bug has been fixed around August last year and has since landed in the central codebase. The fix is now included in the Firefox 51 release that had its final release on January 24th, 2017.

I’m using the Firefox Nightly preview versions and it has been working there properly for a while.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...