如何检查JavaScript中是否存在函数?

时间:2021-07-16 23:50:35

I followed this guide to create a new JS to flash communication.

我跟随这个向导创建了一个新的JS到flash通信。

My code is

我的代码是

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

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

However, sometimes my onChange does not load. Firebug errors with

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

me.onChange is not a function

我。onChange不是一个函数。

I want to degrade gracefully because this is not the most important feature in my program. typeof gives the same error.

我想优雅地降级,因为这不是我的程序中最重要的特性。typeof也会产生相同的错误。

Any suggestions on how to make sure that it exists and then only execute onChange?

关于如何确保它存在,然后只执行onChange的建议?

(None of the methods below except try catch one work)

(下面的方法都没有,只是试着抓住一个工作)

24 个解决方案

#1


813  

Try something like this:

试试这样:

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

or better yet (as per UpTheCreek upvoted comment)

或者更好(根据UpTheCreek的评论)

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

#2


79  

I had this problem.

我有这个问题。

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

kept throwing a reference error if obj happened to be undefined.

如果obj碰巧没有定义,则继续抛出一个引用错误。

In the end I did the following:

最后我做了如下的事:

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

A colleague pointed out to me that checking if it's !== 'undefined' and then === 'function' is redundant of course.

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

Simpler:

简单:

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

Much cleaner and works great.

更干净,效果更好。

#3


44  

Edit: I do not pretend to know the reason(s) why this answer is the accepted one. Please instead use the solution proposed in Andrew Hare's answer: https://*.com/a/1042154/42346

编辑:我不假装知道为什么这个答案是公认的。请使用Andrew Hare给出的解决方案:https://*.com/a/1042154/42346。


Here is one way to handle this kind of situation:

这里有一种处理这种情况的方法:

function js_to_as( str ){
    try {
        me.onChange(str);
    }
    catch(err) {
        // Handle error(s) here
    }
}

#4


13  

If you're using eval to convert a string to function, and you want to check if this eval'd method exists, you'll want to use typeof and your function string inside an eval:

如果您正在使用eval将字符串转换为函数,并且想要检查这个eval'd方法是否存在,那么您将希望在eval中使用typeof和函数字符串:

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

Don't reverse this and try a typeof on eval. If you do a ReferenceError will be thrown:

不要颠倒过来,在eval尝试一种类型。如果你做了一个参考错误将被抛出:

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

#5


6  

Try typeof -- Look for 'undefined' to say it doesn't exist, 'function' for a function. JSFiddle for this code

Try typeof——查找'undefined'表示它不存在,'function'表示函数不存在。JSFiddle这个代码

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

Or as an if:

或作为一个如果:

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

Or with a return value, on a single line:

或以单行返回值:

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

#6


6  

How about:

如何:

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

e.g.

如。

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

or as for your case:

或至于你的情况:

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

See MDN docs.

看到MDN文档。

#7


6  

Didn't see this suggested: me.onChange && me.onChange(str);

没看到这个提示:我。onChange & & me.onChange(str);

Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).

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

You can even go further and do:

你甚至可以更进一步:

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

in case me is async as well.

如果我也是异步的。

#8


4  

I'll go 1 step further to make sure the property is indeed a function

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

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

#9


3  

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

#10


3  

I like using this method:

我喜欢用这种方法:

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

Usage:

用法:

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

#11


2  

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

#12


2  

With no conditions

没有条件

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

#13


2  

I would suspect that me is not getting correctly assigned onload.

我怀疑我没有得到正确的分配。

Moving the get_ID call into the onclick event should take care of it.

将get_ID调用移动到onclick事件应该会处理它。

Obviously you can further trap as previously mentioned:

显然,你可以像前面提到的那样进一步陷入陷阱:

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

#14


2  

I always check like this:

我总是这样检查:

if(!myFunction){return false;}

just place it before any code that uses this function

把它放在任何使用这个函数的代码之前

#15


2  

I had the case where the name of the function varied according to a variable (var 'x' in this case) added to the functions name. This works:

我曾遇到过这样的情况:根据添加到函数名中的变量(这里是var 'x'),函数名会发生变化。如此:

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

#16


2  

The Underscore.js library defines it in the isFunction method as this (which comments suggest may cater for some browser bugs)

下划线。js库在isFunction方法中定义了它(注释表明可能会出现一些浏览器错误)

typeof obj == 'function' || false

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

http://underscorejs.org/docs/underscore.html部分- 143

#17


2  

This simple jQuery code should do the trick:

这个简单的jQuery代码应该可以做到这一点:

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

#18


2  

I have tried the accepted answer; however:

我尝试了公认的答案;然而:

console.log(typeof me.onChange);

returns 'undefined'. I've noticed that the specification states an event called 'onchange' instead of 'onChange' (notice the camelCase).

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

Changing the original accepted answer to the following worked for me:

将最初接受的答案更改为下面的答案对我很有帮助:

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

#19


0  

If you're checking for a function that is a jQuery plugin, you need to use $.fn.myfunction

如果您正在检查一个jQuery插件的函数,那么您需要使用$.fn.myfunction。

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

#20


0  

    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*/
    }

#21


0  

And then there is this...

然后还有这个。

( document.exitPointerLock || Function )();

#22


0  

Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;

这里有一个工作和简单的解决方案,用于检查函数的存在,并通过另一个函数动态地对函数进行分类;

Trigger function

触发函数

function runDynmicFunction(functionname){ 

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

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

and you can now generate the function dynamically maybe using php like this

现在你可以用php动态生成这个函数

function runThis_func(my_Parameter){

    alert(my_Parameter +" triggerd");
}

now you can call the function using dynamically generated event

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

<?php

$name_frm_somware ="runThis_func";

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

?>

the exact HTML code you need is

您需要的确切HTML代码是

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

#23


0  

Try this one:

试试这个:

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

Be aware that I've write this with my cellphone Might contain some uppercase issues and/or other corrections needed like for example functions name

请注意,我用手机写这篇文章时,可能会遇到一些大写的问题和/或其他需要纠正的地方,比如函数名

If you want a function like PHP to check if the var is set:

如果您想要一个像PHP这样的函数来检查var是否设置:

Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}

#24


0  

To illustrate the preceding answers, here a quick JSFiddle snippet :

为了说明前面的答案,这里有一个简短的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
*/

#1


813  

Try something like this:

试试这样:

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

or better yet (as per UpTheCreek upvoted comment)

或者更好(根据UpTheCreek的评论)

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

#2


79  

I had this problem.

我有这个问题。

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

kept throwing a reference error if obj happened to be undefined.

如果obj碰巧没有定义,则继续抛出一个引用错误。

In the end I did the following:

最后我做了如下的事:

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

A colleague pointed out to me that checking if it's !== 'undefined' and then === 'function' is redundant of course.

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

Simpler:

简单:

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

Much cleaner and works great.

更干净,效果更好。

#3


44  

Edit: I do not pretend to know the reason(s) why this answer is the accepted one. Please instead use the solution proposed in Andrew Hare's answer: https://*.com/a/1042154/42346

编辑:我不假装知道为什么这个答案是公认的。请使用Andrew Hare给出的解决方案:https://*.com/a/1042154/42346。


Here is one way to handle this kind of situation:

这里有一种处理这种情况的方法:

function js_to_as( str ){
    try {
        me.onChange(str);
    }
    catch(err) {
        // Handle error(s) here
    }
}

#4


13  

If you're using eval to convert a string to function, and you want to check if this eval'd method exists, you'll want to use typeof and your function string inside an eval:

如果您正在使用eval将字符串转换为函数,并且想要检查这个eval'd方法是否存在,那么您将希望在eval中使用typeof和函数字符串:

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

Don't reverse this and try a typeof on eval. If you do a ReferenceError will be thrown:

不要颠倒过来,在eval尝试一种类型。如果你做了一个参考错误将被抛出:

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

#5


6  

Try typeof -- Look for 'undefined' to say it doesn't exist, 'function' for a function. JSFiddle for this code

Try typeof——查找'undefined'表示它不存在,'function'表示函数不存在。JSFiddle这个代码

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

Or as an if:

或作为一个如果:

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

Or with a return value, on a single line:

或以单行返回值:

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

#6


6  

How about:

如何:

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

e.g.

如。

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

or as for your case:

或至于你的情况:

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

See MDN docs.

看到MDN文档。

#7


6  

Didn't see this suggested: me.onChange && me.onChange(str);

没看到这个提示:我。onChange & & me.onChange(str);

Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).

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

You can even go further and do:

你甚至可以更进一步:

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

in case me is async as well.

如果我也是异步的。

#8


4  

I'll go 1 step further to make sure the property is indeed a function

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

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

#9


3  

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

#10


3  

I like using this method:

我喜欢用这种方法:

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

Usage:

用法:

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

#11


2  

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

#12


2  

With no conditions

没有条件

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

#13


2  

I would suspect that me is not getting correctly assigned onload.

我怀疑我没有得到正确的分配。

Moving the get_ID call into the onclick event should take care of it.

将get_ID调用移动到onclick事件应该会处理它。

Obviously you can further trap as previously mentioned:

显然,你可以像前面提到的那样进一步陷入陷阱:

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

#14


2  

I always check like this:

我总是这样检查:

if(!myFunction){return false;}

just place it before any code that uses this function

把它放在任何使用这个函数的代码之前

#15


2  

I had the case where the name of the function varied according to a variable (var 'x' in this case) added to the functions name. This works:

我曾遇到过这样的情况:根据添加到函数名中的变量(这里是var 'x'),函数名会发生变化。如此:

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

#16


2  

The Underscore.js library defines it in the isFunction method as this (which comments suggest may cater for some browser bugs)

下划线。js库在isFunction方法中定义了它(注释表明可能会出现一些浏览器错误)

typeof obj == 'function' || false

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

http://underscorejs.org/docs/underscore.html部分- 143

#17


2  

This simple jQuery code should do the trick:

这个简单的jQuery代码应该可以做到这一点:

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

#18


2  

I have tried the accepted answer; however:

我尝试了公认的答案;然而:

console.log(typeof me.onChange);

returns 'undefined'. I've noticed that the specification states an event called 'onchange' instead of 'onChange' (notice the camelCase).

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

Changing the original accepted answer to the following worked for me:

将最初接受的答案更改为下面的答案对我很有帮助:

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

#19


0  

If you're checking for a function that is a jQuery plugin, you need to use $.fn.myfunction

如果您正在检查一个jQuery插件的函数,那么您需要使用$.fn.myfunction。

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

#20


0  

    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*/
    }

#21


0  

And then there is this...

然后还有这个。

( document.exitPointerLock || Function )();

#22


0  

Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;

这里有一个工作和简单的解决方案,用于检查函数的存在,并通过另一个函数动态地对函数进行分类;

Trigger function

触发函数

function runDynmicFunction(functionname){ 

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

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

and you can now generate the function dynamically maybe using php like this

现在你可以用php动态生成这个函数

function runThis_func(my_Parameter){

    alert(my_Parameter +" triggerd");
}

now you can call the function using dynamically generated event

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

<?php

$name_frm_somware ="runThis_func";

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

?>

the exact HTML code you need is

您需要的确切HTML代码是

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

#23


0  

Try this one:

试试这个:

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

Be aware that I've write this with my cellphone Might contain some uppercase issues and/or other corrections needed like for example functions name

请注意,我用手机写这篇文章时,可能会遇到一些大写的问题和/或其他需要纠正的地方,比如函数名

If you want a function like PHP to check if the var is set:

如果您想要一个像PHP这样的函数来检查var是否设置:

Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}

#24


0  

To illustrate the preceding answers, here a quick JSFiddle snippet :

为了说明前面的答案,这里有一个简短的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
*/