jQuery: inspecting objects and create a reflection API

jQuery already provides some reflection-like structures to gather information about some JavaScript components. However, we can use the extensibility of the library to get metadata from objects or, if you prefer, classes. More specifically, we want to know if a given member of an object is a property, a method or another object.

Getting properties

We can create the following global function:

$.getProperties = function(obj) {
  
    if(typeof obj !== 'object') {
    
      throw new Error(obj + ' is not an object');
      
      return;
    
    }
    
    var results = [];
    
    for(var property in obj) {
    
      if(obj.hasOwnProperty(property)) {
      
        results.push(property);
      
      }
    
    
    }
    
    return results;
  
};

This function returns an array which contains all the names of the accessible properties of an object. Example:

var A = {
    a: true,
    b: function() {
    
      return this.a;
    
    },
    c: 1,
    
    d: {}
  };
  
var props = $.getProperties(A); // ['a', 'b', 'c', 'd']

Getting methods

The following global function could be used:

$.getMethods = function(obj) {
  
    if(typeof obj !== 'object') {
    
      throw new Error(obj + ' is not an object');
      
      return;
    
    }
    
    var results = [];
    
    for(var property in obj) {
    
      if(obj.hasOwnProperty(property)) {
      
        if(typeof obj[property] === 'function') {
        
          results.push(property);
        
        }
              
      }
    
    
    }
    
    return results;
};

This function returns an array containing all the names of the accessible methods of an object. Example:

var A = {
    a: true,
    b: function() {
    
      return this.a;
    
    },
    c: 1,
    
    d: {}
  };
  
var methods = $.getMethods(A); // ['b']

Getting objects

We can use the following function:

$.getObjects = function(obj) {
  
    if(typeof obj !== 'object') {
    
      throw new Error(obj + ' is not an object');
      
      return;
    
    }
    
    var results = [];
    
    for(var property in obj) {
    
      if(obj.hasOwnProperty(property)) {
      
        if(typeof obj[property] === 'object') {
        
          results.push(property);
        
        }
              
      }
    
    
    }
    
    return results;
  
};

This function returns an array containing all the names of the accessible object contained within the parent object. Example:

var A = {
    a: true,
    b: function() {
    
      return this.a;
    
    },
    c: 1,
    
    d: {}
  };
  
var objects = $.getObjects(A); // ['d']

Leave a Reply

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