我的代码是

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之外都没有)


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

试试这样做:

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

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

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

没有任何条件

me.onChange=function(){};

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

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

我怀疑我没有正确地分配onload。

将get_ID调用移动到onclick事件中应该会解决这个问题。

显然,你可以进一步陷阱,如前所述:

function js_to_as( str) {
  var me = get_ID('jsExample');
  if (me && me.onChange) {
    me.onChange(str);
  }
}

我将进一步确认这个属性确实是一个函数

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

如果你正在使用eval将一个字符串转换为函数,并且你想检查这个eval方法是否存在,你会想在eval中使用typeof和你的函数字符串:

var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"

不要反过来尝试一种类型的eval。如果你这样做,ReferenceError将被抛出:

var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined

我有这个问题。If (obj && typeof obj === 'function'){…如果obj恰好未定义,}会不断抛出引用错误,所以最后我做了以下工作:

if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }

然而,一位同事向我指出,检查它是否为!== 'undefined'然后=== 'function'是多余的,因此:

简单:

if (typeof obj === 'function') { ... }

更干净,工作得很好。


试试typeof——用'undefined'表示它不存在,用'function'表示函数。这段代码的JSFiddle

function thisishere() {
    return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);

或作为if:

if (typeof thisishere === 'function') {
    // function exists
}

或者在一行中返回一个值:

var exists = (typeof thisishere === 'function') ? "Value if true" : "Value if false";
var exists = (typeof thisishere === 'function') // Returns true or false

我总是这样检查:

if(!myFunction){return false;}

只需将它放在任何使用此函数的代码之前


如何:

if('functionName' in Obj){
    //code
}

如。

var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false

至于你的案子

if('onChange' in me){
    //code
}

请参阅MDN文档。


//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");
    }

我喜欢用这个方法:

function isFunction(functionToCheck) {
  var getType = {};
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}

用法:

if ( isFunction(me.onChange) ) {
    me.onChange(str); // call the function with params
}

没有看到这个建议: 我。onChange && me.onChange(str);

基本上如果我。onChange是未定义的(如果它没有被初始化,它将是未定义的),那么它将不会执行后面的部分。如果我。onChange是一个函数,它将执行me.onChange(str)。

你甚至可以更进一步,这样做:

me && me.onChange && me.onChange(str);

以防我也是异步的。


js库在isFunction方法中这样定义它(评论认为这可能会迎合一些浏览器错误)

typeof obj == 'function' || false

http://underscorejs.org/docs/underscore.html#section-143


我有这样的情况,函数的名称根据添加到函数名中的变量(在本例中为var 'x')而变化。如此:

if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); } 

这段简单的jQuery代码应该可以做到:

if (jQuery.isFunction(functionName)) {
    functionName();
}

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

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

我已试过公认的答案;然而:

console.log(typeof me.onChange);

返回“定义”。 我注意到规范中声明了一个名为“onchange”的事件而不是“onchange”(注意camelCase)。

将原来接受的答案更改为以下对我有用:

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

    function sum(nb1,nb2){

       return nb1+nb2;
    }

    try{

      if(sum() != undefined){/*test if the function is defined before call it*/

        sum(3,5);               /*once the function is exist you can call it */

      }

    }catch(e){

      console.log("function not defined");/*the function is not defined or does not exists*/
    }

还有这个…

( document.exitPointerLock || Function )();

这里有一个工作和简单的解决方案,检查一个函数的存在性,并由另一个函数动态触发该函数;

触发函数

function runDynamicFunction(functionname){ 

    if (typeof window[functionname] == "function") { //check availability

        window[functionname]("this is from the function it"); // run function and pass a parameter to it
    }
}

现在可以用PHP动态生成函数

function runThis_func(my_Parameter){

    alert(my_Parameter +" triggerd");
}

现在可以使用动态生成的事件调用该函数

<?php

$name_frm_somware ="runThis_func";

echo "<input type='button' value='Button' onclick='runDynamicFunction(\"".$name_frm_somware."\");'>";

?>

你需要的HTML代码是

<input type="button" value="Button" onclick="runDynamicFunction('runThis_func');">

试试这个:

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;
}

为了说明前面的答案,这里有一个快速的JSFiddle代码片段:

function test () { console.log() } console.log(typeof test) // >> "function" // implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as : // var test = false if(test){ console.log(true)} else{console.log(false)} // test by the typeof method if( typeof test === "function"){ console.log(true)} else{console.log(false)} // confirm that the test is effective : // - entity with false value var test2 = false if(test2){ console.log(true)} else{console.log(false)} // confirm that the test is effective : // - typeof entity if( typeof test ==="foo"){ console.log(true)} else{console.log(false)} /* Expected : function true true false false */


对我来说,最简单的方法是:

function func_exists(fname)
{
  return (typeof window[fname] === 'function');
}

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';
}

放两个感叹号,即!!在要检查的函数名之前。如果它存在,它将返回true。

function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false

我也一直在寻找这个问题的优雅解决方案。经过深思熟虑,我发现这种方法是最好的。

const func = me.onChange ||(str => {}); func(str);


简单来说就是:捕捉异常。

我真的很惊讶在这篇文章中没有人回答或评论异常捕获。

细节:这里有一个例子,我试图匹配一个函数,前缀为mask_,后缀为表单字段“name”。当JavaScript没有找到该函数时,它应该抛出一个ReferenceError,您可以在catch部分进行处理。

函数inputMask(input) { 尝试{ let maskedInput = eval("mask_"+input.name); if(typeof maskedInput === "undefined") 返回input.value; 其他的 返回eval(“mask_”+ input.name)(输入); } catch(e) { if (e instanceof ReferenceError) { 返回input.value; } } }


// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
    console.log( 'write your code here.' );
}

这将验证函数是否存在,如果存在则执行

me.onChange && me.onChange(str);

因此错误TypeError: me。onChange不是一个阻止的函数。


现代JavaScript来拯救!

me.onChange?.(str)

可选链接语法(?.)解决了这个问题

从ES2020开始使用JavaScript 在Typescript版本3.7

在上面的例子中,如果a me。onChange属性存在并且是一个函数,它被调用。

如果没有我。onChange属性存在,则什么也不发生:表达式只是返回undefined。

注——若有我。onChange属性存在但不是函数,将抛出TypeError,就像在JavaScript中调用任何非函数作为函数一样。可选的链接不做任何魔法,使这个消失。


我建议使用:

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);
}

function isFunction( o ) { return null !== o && "function" === typeof o && !!o.apply; }

我更喜欢使用lodash库,如下所示(看起来更干净):

if (_.has(me, "onChange")) {
   // your desired code here
}

// or generic one like

if (_.has(this, "some property or function name")) {
   // your desired code here
}