该函数应该只运行一次。但是我不明白为什么每次调用它时执行的变量都不会返回 false。
var onlyOnce = function() {
var executed = false;
return function() {
if (executed == false) {
executed = true;
console.log("Code reached");
}
};
}();
onlyOnce();
onlyOnce();
此代码仅打印一次。为什么这有效?
最佳答案
这是因为您立即执行一个函数并将 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.这意味着可以在生成的函数内部使用和更改执行的值。无论您将其设置为什么,下次调用它时它仍然具有该值(当然,除非其他东西改变了它)。
关于javascript - 为什么这个功能有效?每次调用该函数时, "executed"不应该返回 false 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339787/