简体   繁体   中英

Is it possible for javascript to break IIFE from another function?

Please see this example code:

(function() {
  if (1 + 1 === 2) {
    return;
  }
  console.log(`This Line Won't Compile`);
})()

The code above simply breaks when the condition is true.

However, I would like to extract the whole logic outside of this 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.`);
})()

How do I achieve this?

Is it possible to achieve this?

You need a flag if the function take short circuit. In this case you need another check and return early.

 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.`); }(); 

There are many options, a simple one would be to set a global variable which you can then use in the 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.`); })() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM