JQuery: utility functions – testing helpers

Published Fri, Aug 7 2009 14:32

One of the things you might need to do is check if a reference is an array or a function. JQuery introduces two simple utility functions for performing these checks: the isArray and the isFunction methods. Both of them expect a single parameter which is used to perform the adequate test. Here’s a really dumb example that shows how to use the isFunction function:

var sayHi = function(name) {
    alert(name);
}
if ($.isFunction(sayHi)) {
    sayHi("Luis");
}

As you can see, we check the sayHi variable and we’ll only invoke it when it is, in fact, a function. These are really simple and rely on the typeof operator for checking the type of an existing reference. For instance, here’s the code for the previous isFunction helper:

isFunction: function( obj ) {
    return toString.call(obj) === "[object Function]";
}

And I guess that sums it up. Keep tuned for more on JQuery.

Filed under:

Comments

# 9eFish said on Sunday, August 09, 2009 8:44 AM

9efish.感谢你的文章 - Trackback from 9eFish

Leave a Comment

(required) 
(required) 
(optional)
(required)