JavaScript: class properties getter

Sometimes it's useful for reflection purposes to retrieve all the properties contained within a given class. Unfortunately, JavaScript doesn't have a native method for that purpose so we have to create one from scratch. For example, given the following class:

function Class() {
  
  this.foo = 'Foo';
  this.bar = 'Bar';
  this.baz = 'Baz';
   
  
}

we can write such a method as follows:

Class.prototype = {
  
  constructor: Class,
  
  getProperties: function() {
   
   var properties = [];
   
   for(var i in this) {
    
    if(typeof this[i] !== 'function') {
     
     properties.push(this[i]);
     
    }
    
    
   }
   
   return properties;
   
  }
  
  
}

This method simply iterates over its own class and stores all property values in an array. A simple test:

var myClass = new Class();
var props = myClass.getProperties();
 
for(var i=0; i<props.length; i++) {
  
 alert(props[i]); //'Foo', 'Bar', 'Baz'
  
}

Very simple.

Leave a Reply

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