javascript检查函数并给出输出(如果存在)

javascript checking for function and giving output if it exists

本文关键字:如果 存在 输出 检查 函数 javascript      更新时间:2023-09-26

我需要一个脚本来检查一个函数是否在页面上,如果在,它会调用一个函数,如果不在,它还会调用另一个函数。我还需要脚本保持在网页上自动输入。

这就是我的想法:

if(Examplefunction) 
  difffunction();
else
  otherfunction();

您需要小心检查JavaScript中可能未定义的名称。引用未定义的名称将产生错误:

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

但是,使用typeof检查名称时,是安全的,无论该名称是否已定义。因此,要检查变量是否已定义为真实值,应使用:

if (typeof Examplefunction != 'undefined' && Examplefunction)
  difffunction();
else
  otherfuunction();
if(typeof name === 'function') {
    name();
}
else {
    // do whatever
}

请注意,这是一个糟糕的设计。例如,你无法检查它需要多少个参数。

它就像:一样简单

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中的一个变量。