Javascript -如何选择性地执行函数/语句

Javascript - How to execute function/statements selectively

本文关键字:执行 函数 语句 选择性 Javascript      更新时间:2023-09-26

不确定这是否是命名这个问题的最佳方式,但我有以下不喜欢在严格模式下运行的代码。我需要根据if条件设置runstatementshere()函数的内容/语句。然后runstatementshere()将作为另一个函数的一部分运行,并成为该作用域的一部分。

    if (i == true) {
        function runstatementshere() {
            // multiline commands
        };
    }
    else {
        function runstatementshere() {
        }
    }
    function somecode() {
        runstatementshere();
    }

先看这个答案。

函数声明似乎是允许的,但在包含块中提升。我不确定这是否是定义行为,但Chrome和Firefox是这样做的。

它们的行为是这样的,因为如果这两个函数在if语句的范围内提升,后者总是获胜。

无论如何,要解决您的问题,请使用函数表达式。

"use strict";
var runstatementshere;
if (true) {
  runstatementshere = function() { console.log("a"); }
} else {
  runstatementshere = function() { console.log("b"); }
}
function somecode() {
  runstatementshere();
}
somecode();

最简单的方法是:

function firstFunction() {
  console.log(1);
}
function secondFunction() {
  console.log(2);
}
function somecode() {
  if (i) {
    firstFunction();
  } else {
    secondFunction();
  }
}
var i = false;
somecode();

但是如果你有很好的理由不在somecode()中使用if,那么试试这种方式来声明函数。

你代码中的问题是你在同一个作用域中声明了同一个函数两次。

var runstatementshere, i = false;
if (i == true) {
  runstatementshere = function() {
    console.log(1);
  };
} else {
  runstatementshere = function() {
    console.log(2);
  };
}
function somecode() {
  runstatementshere();
}
somecode();

这应该在严格模式下编译。但不知何故是荒谬的…因为在函数体中包含条件更符合逻辑。但是你仍然可以很好地利用它。

(function(){
var myFunction = i ? function() {} : function () {};
function a()
{
  myFunction();
}}
)()

重写它,这样你就有一个函数构造器了。

var myFunctionConstructor = function(i) {
     return i ? function() {} : function () {};
}

var myFunction = myFunctionConstructor(false);
myFunction(); // first function called
myFunction = myFunctionConstructor(true);
myFunction(); // second function called