[英]Is it possible for javascript to break IIFE from another function?
請參見以下示例代碼:
(function() {
if (1 + 1 === 2) {
return;
}
console.log(`This Line Won't Compile`);
})()
當條件為真時,上面的代碼就會中斷。
但是,我想從IIFE中提取整個邏輯。
function checkNumber() {
if (1 + 1 === 2) {
return;
}
}
(function() {
checkNumber(); // How do I achieve this?
console.log(`This Line Now Compile, but I don't want this line compile.`);
})()
我該如何實現?
有可能實現這一目標嗎?
如果功能短路,則需要標記。 在這種情況下,您需要再次檢查並盡早返回。
function checkNumber() { if (1 + 1 === 2) { return true; // supply a flag } } void function() { console.log('IIFE'); if (checkNumber()) return; // use this flag console.log(`This Line Now Compile, but I don't want this line compile.`); }();
有很多選項,一個簡單的選擇就是設置一個全局變量,然后可以在IIFE中使用
var iAmAGlobalVariableKnowingWhatToDo = false; var checkNumber = function () { if (1 + 1 === 2) { iAmAGlobalVariableKnowingWhatToDo = true; return; } iAmAGlobalVariableKnowingWhatToDo = false; }; // note everything until this line of code is in the global scope! // that's why you can use the checkNumber() and the variable inside the IIFE (function() { checkNumber(); if(iAmAGlobalVariableKnowingWhatToDo) { return; } console.log(`This Line Now Compile, but I don't want this line compile.`); })()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.