【问题标题】:check if a javascript function is exist or is defind [duplicate]检查javascript函数是否存在或已定义[重复]
【发布时间】:2013-12-21 05:55:33
【问题描述】:

我想知道一个函数是否存在或在我调用它之前被定义。

我有这行代码:

function renderView(){
 // some code
}

【问题讨论】:

标签: javascript function


【解决方案1】:

您可以检查 typeof,如果未定义或超出范围,则返回 undefined,如果是函数,则返回 function

if ( typeof renderView == 'function' ) {
    // it exists
}

【讨论】:

  • 感谢您使用 typeof 作为运算符,而不是像所有其他傻瓜一样使用函数 :)
  • //Simple function that will tell if the function is defined or not function is_function(func) { return typeof window[func] !== 'undefined' && $.isFunction(window[func]); } //usage if (is_function("myFunction") { alert("myFunction defined"); } else { alert("myFunction not defined"); }
  • 使用 jQuery 并假设函数是在全局范围内定义的?
猜你喜欢
  • 2018-05-21
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 2015-09-27
  • 2022-01-08
相关资源
最近更新 更多