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

时间:2019-06-15 18:49:56

标签: javascript

请参见以下示例代码:

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

我该如何实现?

有可能实现这一目标吗?

2 个答案:

答案 0 :(得分:2)

如果该功能短路,则需要一个标志。在这种情况下,您需要再次检查并尽早返回。

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

答案 1 :(得分:0)

有很多选项,一个简单的选择就是设置一个全局变量,然后可以在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.`);
})()