2014-07-27 30 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 
} 

注意这是可怕的设计。例如,你不能检查它期望的参数。

相关问题