简体   繁体   English

JavaScript是否有可能打破IIFE的另一个功能?

[英]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. 但是,我想从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 有很多选项,一个简单的选择就是设置一个全局变量,然后可以在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.

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