Hướng dẫn check function exists 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. Firebug errors with

me.onChange is not a function

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

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

[None of the methods below except try catch one work]

animuson

52.8k28 gold badges139 silver badges145 bronze badges

asked Jun 25, 2009 at 4:10

Alec SmartAlec Smart

91.5k38 gold badges118 silver badges181 bronze badges

4

Try something like this:

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

or better yet [as per UpTheCreek upvoted comment]

if [typeof me.onChange === "function"] { 
    // safe to use the function
}

j0k

22.3k28 gold badges77 silver badges86 bronze badges

answered Jun 25, 2009 at 4:14

Andrew HareAndrew Hare

337k71 gold badges633 silver badges630 bronze badges

14

I had this problem. if [obj && typeof obj === 'function'] { ... } kept throwing a reference error if obj happened to be undefined, so in the end I did the following:

if [typeof obj !== 'undefined' && typeof obj === 'function'] { ... }

However, a colleague pointed out to me that checking if it's !== 'undefined' and then === 'function' is redundant, thus:

Simpler:

if [typeof obj === 'function'] { ... }

Much cleaner and works great.

ashleedawg

19.4k7 gold badges69 silver badges100 bronze badges

answered Feb 6, 2013 at 23:27

Misha NasledovMisha Nasledov

1,8931 gold badge14 silver badges18 bronze badges

3

Modern JavaScript to the rescue!

me.onChange?.[str]

The Optional Chaining syntax [?.] solves this

  • in JavaScript since ES2020
  • in Typescript since version 3.7

In the example above, if a me.onChange property exists and is a function, it is called.

If no me.onChange property exists, nothing happens: the expression just returns undefined.

If a me.onChange property exists but is not a function, a TypeError will be thrown just like when you call any non-function as a function in JavaScript. Optional Chaining doesn't do any magic to make this go away.

answered Mar 3, 2020 at 15:57

7

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.

answered Feb 10, 2015 at 16:15

1

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:

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:

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

answered May 27, 2011 at 21:50

dhulihandhulihan

10.8k8 gold badges38 silver badges45 bronze badges

2

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

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

answered Aug 14, 2013 at 20:32

Mat CarlsonMat Carlson

5233 silver badges12 bronze badges

Didn't see this suggested: 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. If me.onChange is a function, it will execute me.onChange[str].

You can even go further and do:

me && me.onChange && me.onChange[str];

in case me is async as well.

answered Jan 18, 2016 at 20:04

Samir AlajmovicSamir Alajmovic

3,2013 gold badges26 silver badges28 bronze badges

0

For me the easiest way :

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

answered Aug 27, 2018 at 12:21

Tu4n3rTu4n3r

4115 silver badges10 bronze badges

1

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

answered Apr 23, 2015 at 13:14

3

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: //phpjs.org/functions/function_exists/
  // original by: Kevin van Zonneveld [//kevin.vanzonneveld.net]
  // improved by: Steve Clay
  // improved by: Legaev Andrey
  // improved by: Brett Zamir [//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';
}

answered Oct 11, 2018 at 6:49

2

Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.

function abc[]{
}
!!window.abc; // return true
!!window.abcd; // return false

answered Dec 15, 2018 at 15:43

function js_to_as[ str ]{
     if [me && me.onChange]
         me.onChange[str];
}

answered Jun 25, 2009 at 4:13

MiffTheFoxMiffTheFox

21k14 gold badges67 silver badges92 bronze badges

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

answered Jun 25, 2009 at 8:04

AlexAlex

33k10 gold badges52 silver badges68 bronze badges

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
}

answered Aug 13, 2015 at 17:08

David DouglasDavid Douglas

10.3k2 gold badges53 silver badges53 bronze badges

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:

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

answered Mar 18, 2016 at 14:02

0

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

if [typeof $.fn.mask === 'function'] {
    $['.zip'].mask['00000'];
}

Evg

23.5k5 gold badges40 silver badges75 bronze badges

answered Feb 15, 2017 at 15:24

Lucas BustamanteLucas Bustamante

14.4k7 gold badges82 silver badges81 bronze badges

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

function runThis_func[my_Parameter]{

    alert[my_Parameter +" triggerd"];
}

now you can call the function using dynamically generated event

Chủ Đề