我的代码是

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}

然而,有时我的onChange不加载。Firebug错误

我。onChange不是一个函数

我想优雅地降级,因为这不是我的程序中最重要的特性。Typeof给出相同的错误。

关于如何确保它存在,然后只执行onChange有什么建议吗?

(下面的方法除了try catch one work之外都没有)


当前回答

试试这样做:

if (typeof me.onChange !== "undefined") { 
    // safe to use the function
}

或者更好(根据upcreek的upvotes评论)

if (typeof me.onChange === "function") { 
    // safe to use the function
}

其他回答

function js_to_as( str ){
     if (me && me.onChange)
         me.onChange(str);
}

我建议使用:

function hasMethod(subject, methodName) {
  return subject != null && typeof subject[methodName] == "function";
}

第一个检查主题!= null过滤掉没有任何属性的null值(null和undefined)。如果没有这个检查,主题[methodName]可能会抛出一个错误:

TypeError:(undefined|null)没有属性

只检查一个真值是不够的,因为0和""都是假的,但确实有属性。

在确认subject不是null之后,你可以安全地访问属性并检查它是否匹配typeof subject[methodName] == "function"。


将此应用到您的代码,您现在可以做到:

if (hasMethod(me, "onChange")) {
  me.onChange(str);
}

如果你正在检查一个函数是否是jQuery插件,你需要使用$.fn.myfunction

if (typeof $.fn.mask === 'function') {
    $('.zip').mask('00000');
}

试试这个:

Window.function_exists=function(function_name,scope){
//Setting default scope of none is provided
If(typeof scope === 'undefined') scope=window;
//Checking if function name is defined
If (typeof function_name === 'undefined') throw new 
Error('You have to provide an valid function name!');
//The type container
var fn= (typeof scope[function_name]);
//Function type
If(fn === 'function') return true;
//Function object type
if(fn.indexOf('function')!== false) return true; 
return false;
}

请注意,这是我用手机写的 可能包含一些大写问题和/或其他需要的更正,例如函数名

如果你想让PHP这样的函数检查是否设置了var:

Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}
function function_exists(function_name)
{
    return eval('typeof ' + function_name) === 'function';
}
alert(function_exists('test'));
alert(function_exists('function_exists'));

OR

function function_exists(func_name) {
  //  discuss at: http://phpjs.org/functions/function_exists/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Steve Clay
  // improved by: Legaev Andrey
  // improved by: Brett Zamir (http://brett-zamir.me)
  //   example 1: function_exists('isFinite');
  //   returns 1: true

  if (typeof func_name === 'string') {
    func_name = this.window[func_name];
  }
  return typeof func_name === 'function';
}