简体   繁体   English

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

[英]How to check if function exists in JavaScript?

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.但是,有时我的onChange不会加载。 Firebug errors with Firebug 错误与

me.onChange is not a function me.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) (除了 try catch 一项工作外,没有以下方法)

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
}

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.更清洁,效果很好。

Modern JavaScript to the rescue!现代 JavaScript 来救援!

This is solved in JavaScript since ES2020 , and Typescript since v3.7 , with Optional Chaining .ES2020以来,这在 JavaScript 中得到解决,自v3.7起在 Typescript 中使用Optional Chaining解决。

me.onChange?.(str)

If onChange exists, it gets called.如果onChange存在,它会被调用。

If onChange does not exist, nothing happens: the expression returns undefined .如果onChange不存在,则什么也不会发生:表达式返回undefined

So for let value = me.onChange?.(str) , value is undefined if onChange does not exist.因此,对于let value = me.onChange?.(str) ,如果onChange不存在,则value未定义。

Note, if onChange exists but is not a function, it throws a TypeError just the same as if you call any non-function as a function.注意,如果onChange存在但不是一个函数,它会抛出一个TypeError就像你将任何非函数调用为函数一样。 Optional Chaining doesn't do any magic to make this go away.可选的链接并没有做任何魔法来消除这种情况。

How about:怎么样:

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

eg例如

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 文档

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 方法是否存在,则需要在eval中使用typeof和函数字符串:

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

Don't reverse this and try a typeof on eval .不要扭转这一点并在eval上尝试typeof If you do a ReferenceError will be thrown:如果您这样做,将抛出 ReferenceError:

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

Try typeof -- Look for 'undefined' to say it doesn't exist, 'function' for a function.尝试typeof - 查找'undefined'表示它不存在,查找'function'表示函数。 JSFiddle for this code此代码的 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

Didn't see this suggested: me.onChange && me.onChange(str);没有看到这个建议:me.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.基本上,如果 me.onChange 未定义(如果尚未启动,它将是),那么它将不会执行后一部分。 If me.onChange is a function, it will execute me.onChange(str).如果 me.onChange 是一个函数,它将执行 me.onChange(str)。

You can even go further and do:你甚至可以更进一步,做:

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

in case me is async as well.以防我也是异步的。

For me the easiest way :对我来说最简单的方法:

function func_exists(fname)
{
  return (typeof window[fname] === 'function');
}
//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");
    }

Put double exclamation mark ie !!放双感叹号即!! before the function name that you want to check.在要检查的函数名称之前。 If it exists, it will return true.如果存在,它将返回 true。

function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false
function js_to_as( str ){
     if (me && me.onChange)
         me.onChange(str);
}

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

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
}

The Underscore.js library defines it in the isFunction method as this (which comments suggest may cater for some browser bugs) Underscore.js 库在 isFunction 方法中将其定义为 this (评论建议可能会满足某些浏览器错误)

typeof obj == 'function' || false

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

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.我遇到了函数名称根据添加到函数名称中的变量(在本例中为 var 'x' )而变化的情况。 This works:这有效:

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

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

Here is a working and simple solution for checking existence of a function and triggering that function dynamically by another function;这是用于检查功能是否存在并由另一个功能动态触发该功能的有效且简单的解决方案;

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

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='runDynamicFunction(\"".$name_frm_somware."\");'>";

?>

the exact HTML code you need is您需要的确切 HTML 代码是

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

In a few words: catch the exception.简而言之:捕获异常。

I am really surprised nobody answered or commented about Exception Catch on this post yet.我真的很惊讶没有人在这篇文章中回答或评论 Exception Catch。

Detail: Here goes an example where I try to match a function which is prefixed by mask_ and suffixed by the form field "name".详细信息:这是一个示例,我尝试匹配一个以 mask_ 为前缀并以表单字段“name”为后缀的函数。 When JavaScript does not find the function, it should throw an ReferenceError which you can handle as you wish on the catch section.当 JavaScript 没有找到该函数时,它应该抛出一个ReferenceError ,您可以在 catch 部分随意处理它。

 function inputMask(input) { try { let maskedInput = eval("mask_"+input.name); if(typeof maskedInput === "undefined") return input.value; else return eval("mask_"+input.name)(input); } catch(e) { if (e instanceof ReferenceError) { return input.value; } } }

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

I would suspect that me is not getting correctly assigned onload.我怀疑me没有正确分配 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);
  }
}

I always check like this:我总是这样检查:

if(!myFunction){return false;}

just place it before any code that uses this function只需将其放在使用此功能的任何代码之前

This simple jQuery code should do the trick:这个简单的 jQuery 代码应该可以解决问题:

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

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
}

I have also been looking for an elegant solution to this problem.我也一直在寻找一个优雅的解决方案来解决这个问题。 After much reflection, I found this approach best.经过多次思考,我发现这种方法最好。

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

I would suggest using:我建议使用:

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

The first check subject != null filters out nullish values ( null and undefined ) which don't have any properties.第一个检查subject != null过滤掉没有任何属性的空值( nullundefined )。 Without this check subject[methodName] could throw an error:如果没有此检查, subject[methodName]可能会引发错误:

TypeError: (undefined|null) has no properties TypeError: (undefined|null) 没有属性

Checking for only a truthy value isn't enough, since 0 and "" are both falsy but do have properties.仅检查真值是不够的,因为0""都是假的,但确实具有属性。

After validating that subject is not nullish you can safely access the property and check if it matches typeof subject[methodName] == "function" .在验证该subject不为空后,您可以安全地访问该属性并检查它是否与typeof subject[methodName] == "function"匹配。


Applying this to your code you can now do:将此应用到您的代码中,您现在可以执行以下操作:

if (hasMethod(me, "onChange")) {
  me.onChange(str);
}
    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 )();

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

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

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

This will verify if the function exists, if so it will be executed这将验证函数是否存在,如果存在则执行

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

Thus the error TypeError: me.onChange is not a function is prevent.因此错误TypeError: me.onChange is not a function被阻止。

I prefer it using lodash library as below (looks much cleaner):我更喜欢使用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
}
function isFunction( o ) { return null !== o && "function" === typeof o && !!o.apply; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM