Find out if type has property

65 Views Asked by At

I have a type defined like this:

function Type(){} ;

I also have a class that creates types dynamically so I pass the type.

function Factory(Type){};

I need to check wether the type has any given property. My question is similar to this, but I need to check on type not on object.

[UPDATE] I have tried creating a temporary object which works for some of my types, but some of my types require some arguments on the constructor which throw exceptions if the correct argument types are not found.

1

There are 1 best solutions below

1
On BEST ANSWER

There's nothing in the language to enforce that all objects of a class have the same set of properties. Constructors can decide what properties to create based on the arguments, and as the question points out, the arguments aren't available.

If you won't have an instance of the object, you should use a convention of your own to make this information available from the class itself.

One idea is to initialize all properties on the class's prototype, e.g.:

function Type(owner) {
    this.owner = owner;
}
Type.prototype.owner = null;
Type.prototype.counter = 0;
Type.prototype.increment = function () {
    this.counter++;
};

Then, in Factory,

if ('counter' in Type.prototype) {
    ...
}
if ('owner' in Type.prototype) {
    ...
}

This will only work as long as you follow your own rules.