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

时间:2016-10-22 20:59:28

标签: javascript

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

    if (i == true) {

        function runstatementshere() {

            // multiline commands
        };

    }

    else {

        function runstatementshere() {

        }

    }

    function somecode() {

        runstatementshere();

    }

3 个答案:

答案 0 :(得分:0)

Read this answer first.

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

他们的行为就是这样,因为如果这两个函数在if语句的范围内被提升,后者总会赢。

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

"use strict";

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

function somecode() {
  runstatementshere();
}

somecode();

答案 1 :(得分:-1)

最简单的方法是:



function firstFunction() {
  console.log(1);
}

function secondFunction() {
  console.log(2);
}

function somecode() {
  if (i) {
    firstFunction();
  } else {
    secondFunction();
  }
}

var i = false;

somecode();




但如果您有充分的理由不在if内使用somecode(),请尝试使用这种方式声明函数。

代码中的问题是您在同一范围内两次声明相同的函数。



var runstatementshere, i = false;

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

function somecode() {
  runstatementshere();
}

somecode();




答案 2 :(得分:-2)

这应该在严格模式下编译..但在某种程度上是荒谬的...因为在函数体中包含一个条件更合乎逻辑。但是你仍然可以很好地利用它。

(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