4

In Javascript, I want to check if an attribut (or object) is a function or not.

My Present code:

if (this.execute != null)
{
    this.execute();
}

Error: Object doesn't support this property or method.

i want to do something like

if (this.execute != null and isExecutableFunction(this.execute)== true )
{
    this.execute();
}

Is there anyway in Javascript to check if an attribute (or object ) is a function or not
Any help shall be appreciated.
Thanks.

rjdthegreat
  • 204
  • 3
  • 10
  • Try this thread on clj: https://groups.google.com/group/comp.lang.javascript/browse_frm/thread/792457773ca7cf01/ee41f692d8595b58?hl=en#ee41f692d8595b58 For native objects, `typeof foo == 'function'` is sufficient, however for host objects it is not sufficient. – RobG Apr 21 '11 at 13:19
  • I think you mean Argument not Attribute... – Nate-Wilkins Aug 16 '13 at 17:37
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+check+if+value+is+function) of (higher-quality) [Check if a variable is of function type](https://stackoverflow.com/q/5999998/4642212). – Sebastian Simon Mar 14 '21 at 04:09

3 Answers3

10

Try this:

if(typeof this.execute == 'function') { 
this.execute(); 
}
0

You could use typeof

var func = function(){};
alert(typeof func)

If you put this in your firebug console and run it, you get function as the return.

So you just need to check for it.

JohnP
  • 49,507
  • 13
  • 108
  • 140
-1

Try this. Works fine in jsfiddle. I changed this to t since I wasn't working inside a function. Try it with line 2 both remarked and unremarked.

var t= new Object;

//t.execute = function() { alert('executing'); };

if(t.execute)  
   t.execute();
else
    //code here when execute fails
  alert('Function could not execute');
Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91
  • 1
    That only tests if *t.execute* is truthy, it doesn't indicate whether it's callable or not. – RobG Apr 21 '11 at 13:27
  • Apparently it turns out my function is not null (Hence the if will pass) and it is not a callable function either hence fails. Seems we have to check for ' typeof (t.execute.constructor) == 'function' ' But thanks a ton for the answer. God Bless. Cheers! – rjdthegreat Apr 28 '11 at 02:35