2014-07-27 26 views

回答

0

你必須要小心檢查,可能沒有在JavaScript中定義的名稱。引用未定義將產生一個錯誤的名稱:檢查與typeof名稱

> if (Examplefunction) console.log('exists'); else console.log('???') 
ReferenceError: Examplefunction is not defined 

,然而,安全,這個名字是否已經被定義或沒有。因此,要檢查一個變量是否被定義爲一個truthy值,你應該使用:

if (typeof Examplefunction != 'undefined' && Examplefunction) 
    difffunction(); 
else 
    otherfuunction(); 
0

很簡單:

if(funcNameHere){ 
    funcNameHere(); // executes function 
    console.log('function exists'); 
} 
else{ 
    someOtherFunction(); // you can always execute another function 
    console.log("function doesn't exist"); 
} 

想要讓一個函數,它說明了一切:

function funcSwitch(func1, func2){ 
    var exc = func1 ? func1 : func2; 
    exc(); 
} 
// check to see if `firstFunction` exists then call - or call `secondFunction` 
fucSwitch(firstFunction, secondFunction); 

當然,如果您不傳遞一個函數變量,它將不起作用。函數名稱基本上是一個在JavaScript中使用()執行的變量。如果你習慣了PHP,那麼函數名必須是一個String。這是JavaScript中的一個變量。

0
if(typeof name === 'function') { 
    name(); 
} 
else { 
    // do whatever 
} 

注意這是可怕的設計。例如,你不能檢查它期望的參數。

相關問題