此功能应该只运行一次。但是我不明白为什么每次被调用时执行的变量都不会返回false。
var onlyOnce = function() {
var executed = false;
return function() {
if (executed == false) {
executed = true;
console.log("Code reached");
}
};
}();
onlyOnce();
onlyOnce();

此代码仅打印一次。为什么这样做?
答案 0 :(得分:2)
这是因为您立即执行了一项功能并将onlyOnce
设置为该结果。你可以像这样重写它:
function createOnlyOnce() {
var executed = false;
return function() { // Return a new function
if (!executed) { // I prefer this over == false
executed = true;
console.log('Code reached');
}
};
}
var onlyOnce = createOnlyOnce(); // Created a new function
onlyOnce(); // Calls the generated function, not createOnlyOnce
onlyOnce(); // Since we're calling the generated function, executed is still `true`
您最终得到的是closure.这意味着executed
的值可以在生成的函数内使用和更改。无论你把它设置为什么,下次你打电话时它仍然具有那个价值(当然,除非别的东西改变它)。
答案 1 :(得分:0)
使用自执行外部函数,创建一个闭包。因此,返回函数的每次执行都在executed
的同一个实例上运行。这导致观察到的行为。
您应该阅读闭包e.g. on MDN。