jQuery: reflection API functions

jQuery provides several utility functions that can be used to add an extra level of introspection to our code. Among these functions, there are four functions that are particularly useful for implementing a reflection routine on our code. These include:

isArray()

Determines whether the argument is an array.

Example
var Class = {


    collection: [1, 2, 3, 4],
    
    orderCollection: function(arr) {
    
       
       if(!$.isArray(arr)) {
       
       
           throw new Error('orderCollection() accepts only arrays');
       
       }
       
       // other code
    
    
    }


};

isEmptyObject()

Check to see if an object is empty (contains no properties).

Example

var Class = {


   factorize: function() {
   
       var o = {};
       
       return o;
   
   
   },
   
   getInstance: function(obj) {
   
   
       if(!$.isEmptyObject(obj)) {
       
       
           throw new Error('getInstance accepts only empty objects.');
       
       }   
   
   }
   
   // other code


};

isFunction()

Determine if the argument passed is a Javascript function object.

Example
var Class = {

    method: function() {
    
        alert('Test');
    
    },
    
    
    autoload: function() {
    
    
        for(var i in this) {
        
        
            if($.isFunction(this[i]) && this[i] !== arguments.callee) {
            
            
                this[i]();
            
            }
        
        
        }
    
    
    }


};

isPlainObject()

Check to see if an object is a plain object (created using {} or new Object).

Example
var Class = {

    newInstance: function() {
    
    
        var o = new Object();
        
        return o;
    
    },
    
    getInstance: function(obj) {
    
    
        if(!$.isPlainObject(obj)) {
        
        
            throw new Error('getInstance accepts only plain objects.');
        
        }
        
    
    }
    
    // other code


};

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.