Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object has a function? (DoJo)

var testObj = this.getView(); 

How can I check with DoJo (or just native JS) if testObj has callableFunction before I actually try to call callableFunction() and fail if it isn't there? I would prefer a native-DoJo solution as I need this to work on all browsers.

like image 962
antonpug Avatar asked Feb 19 '13 16:02

antonpug


People also ask

How do you check if an object has a function?

Use the typeof operator to check if an object contains a function, e.g. typeof obj. sum === 'function' . The typeof operator returns a string that indicates the type of the value.

Is an object a function?

Object is a function, but not every object is a function.

How do you check if an object is a type?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.


1 Answers

You can call it like this:

testObj.callableFunction && testObj.callableFunction(); 

or in details:

if (typeof testObj.callableFunction == 'function') {     testObj.callableFunction(); } 
like image 102
dfsq Avatar answered Oct 12 '22 03:10

dfsq