Reflection API in jQuery

Reflection API in jQuery

jQuery fornisce diverse funzioni assistive che semplificano notevolmente la vita degli sviluppatori. Quattro di queste funzioni si rivelano utili qualora volessimo implementare una sorta di reflection API in jQuery. Ricordiamo che JavaScript manca di una caratteristica fondamentale presente in altri linguaggi, ossia il type hinting. Queste funzioni sono:

$.isArray()

Verifica che l'argomento passato sia un array.

Esempio


var Class = {
    
    orderCollection: function(arr) {
    
       
       if(!$.isArray(arr)) {
       
       
           throw new Error('orderCollection() accetta solo array.');
       
       }
       
    
    
    }


};

$.isEmptyObject()

Verifica che un oggetto sia vuoto, ossia che non contenga proprietà.

Esempio


var Class = {
   
   getAnotherInstance: function(obj) {
   
   
       if(!$.isEmptyObject(obj)) {
       
       
           throw new Error('getAnotherInstance() accetta solo oggetti vuoti.');
       
       }   
   
   }
   


};

$.isFunction()

Verifica se l'argomento passato è una funzione JavaScript.

Esempio


var Class = {

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


};

$.isPlainObject()

Verifica che un oggetto sia stato creato usando {} o new Object.

Esempio


var Class = {

    
    getObject: function(obj) {
    
    
        if(!$.isPlainObject(obj)) {
        
        
            throw new Error('getObject() accetta solo oggetti semplici.');
        
        }
        
    
    }
    


};
Torna su