2016-10-22 28 views
-1

不知道這是否是命名此問題的最佳方式,但我有以下代碼,它不喜歡在嚴格模式下運行。我需要設置runstatementshere()函數的內容/語句,具體取決於if條件。然後runstatementshere()將作爲另一個函數的一部分運行併成爲該範圍的一部分。Javascript - 如何選擇性地執行函數/語句

if (i == true) { 

     function runstatementshere() { 

      // multiline commands 
     }; 

    } 

    else { 

     function runstatementshere() { 

     } 

    } 

    function somecode() { 

     runstatementshere(); 

    } 
+2

爲什麼不把'if'聲明'runstatementshere'函數內? – 4castle

+1

使用函數表達式將函數分配給在更高範圍聲明的變量而不是函數聲明。然後,您可以根據您的if語句爲變量分配不同的函數實現。 – jfriend00

+0

你不應該在條件內定義一個函數 –

回答

-2

這應在嚴格模式編譯..但是某種無意義..因爲這將是更合乎邏輯包括在函數體的條件。但是你仍然可以很好地使用它。

(function(){ 

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

)() 

Rewirite它讓你有一個函數的構造..

var myFunctionConstructor = function(i) { 

    return i ? function() {} : function() {}; 
} 


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

'somecode()'的函數體運行很多次,所以我不想在那裏有一個IF。我希望我的IF在'somecode()'之外。 –

+0

@ Zertix.net - 如果一個函數中的單個「if」有任何區別,那將是不尋常的。 – jfriend00

+0

@ jfriend00對於工廠構造函數來說,它會有點意義。工廠構造函數 –

-1

最簡單的方法是:

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

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

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

 
var i = false; 
 

 
somecode();

但是,如果你有一個很好的理由不要在內使用,試試這種聲明函數的方法。

你的代碼中的問題是你在相同的作用域中聲明兩次相同的函數。

var runstatementshere, i = false; 
 

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

 
function somecode() { 
 
    runstatementshere(); 
 
} 
 

 
somecode();

+0

你不應該在條件裏面定義一個函數 –

+0

@CarlMarkham:爲什麼? –

+0

因爲它們可能會導致不一致,並且不是ECMAScript的一部分.T –

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();