我正在阅读this文章 还有一段话:
If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:
(function() {
var myProperty = "hello world";
alert(myProperty);
})();
alert(typeof(myProperty)); // undefined
我已经遇到过这个问题,但仍然需要一些澄清,当变量在 Javascript 中的函数内隐式限定作用域时,为什么我需要显式地在函数内限定变量的作用域。
您能解释一下这样做的目的吗?
谢谢
最佳答案
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i) }, 10);
}
// alerts 10, 10 times
for (var i = 0; i < 10; i++) {
(function(i) {
// explicitly scope i
setTimout(function() { console.log(i) }, 10);
})(i);
}
当在其他函数内生成函数并通过闭包作用域访问作用域链上游的变量时,在外部函数内“显式作用域”变量可能会很有用。
尽管这是一种反模式。正确的解决方案是
var generateLogger = function(i) {
return function() { console.log(i); };
}
for (var i = 0; i < 10; i++) {
setTimeout(generateLogger(i), 10);
}
因为在循环中生成函数是低效且不好的做法。
不存在无法通过不在其他函数内创建函数来避免“显式界定”变量的实际用例。
关于javascript - 在函数内显式定义变量的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7401906/