jeudi 28 mai 2015

Get the public properties of a class without creating an instance of it?

Let's imagine that we have a JavaScript class:

var Person = (function () {
    function Person(name, surname) {
        this.name = name;
        this.surname = surname;
    }
    Person.prototype.saySomething = function (something) {
        return this.name + " " + this.surname + " says: " + something;
    };
    return Person;
})();

I want to iterate its methods and properties. I have no problem with the methods.

  var proto = Person.prototype,
      methods = Object.keys(proto);

  // iterate class methods ["saySomething"]
  for (var i = 0; i < methods.length; i++) {
    // do something...
  }

My problem comes when I want to iterate its properties:

  var proto = Person.prototype,
      targetInstance = new Person(), // this is my problem!
      properties = Object.getOwnPropertyNames(targetInstance),

  // iterate class properties ["name", "surname"]
  for (var i = 0; i < properties.length; i++) {
    // do something...
  }

The only way that I have found is to create an instance and use Object.getOwnPropertyNames. I want to use this code as part of a framework so I will not have control over the classes defined by other developers. I want to avoid the need of creating an instance because if the constructor had some sort of validation like:

function Person(name, surname) {

  if(typeof name === "undefined" || typeof surname === "undefined"){ 
    throw new Error() 
  }

  this.name = name;
  this.surname = surname;
}

I wouldn't be able to use the code above. Do you know if it is possible to get the public properties of a class without creating an instance of it?





Aucun commentaire:

Enregistrer un commentaire