javascript:如何判断函数名称是否存在? [英] javascript: how to judge a function name exists?

查看:71
本文介绍了javascript:如何判断函数名称是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在调用函数之前判断函数名称是否存在?

Is it possible to judge if a function names exists before calling it?

推荐答案

您需要检查typeof该功能,例如:

You an check typeof for the function, for example:

if(typeof this["functionName"] != "undefined") {
  alert("uh oh, doesn't exist");
}

如果您需要检查它是否存在并且需要特别确保该功能:

If you need to check if it exists and is a function to be extra sure:

if(typeof this["functionName"] == "function") {
  this["functionName"](); //it exists, call it
}


或更宽松的版本:


Or the more relaxed version:

if(this["functionName"]) this["functionName"]();

如果名称没有更改(例如,我误解了问题),请使用点符号,如下所示:

If the name doesn't change (e.g. I misinterpreted the question) just use dot notation, like this:

if(this.functionName) this.functionName();

或者当然不必一定是this ...无论您要检查的对象是什么,如果它是全局函数,请使用window.

Or course it doesn't have to be this...whatever object you're checking on, use that, if it's a global function use window.

这篇关于javascript:如何判断函数名称是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆