-2

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.

Community
  • 1
  • 1
d0001
  • 2,162
  • 3
  • 20
  • 46
  • 2
    *"check whether the type has property"*. More details here. What property? – dfsq Dec 19 '14 at 19:37
  • Instead of checking the type for the property can you create an instance of `type` and then use `hasOwnProperty`?... – War10ck Dec 19 '14 at 19:38
  • @War10ck Pleas see update – d0001 Dec 19 '14 at 19:41
  • 1
    @Daniel did you create the class yourself? If so, just build some type checking to ensure the type is correct. Either way, your question is unclear. Please explain what exactly goes wrong with the method described in [UPDATE]. – Joeytje50 Dec 19 '14 at 19:46
  • @Joeytje50 UPDATE method does not work if Type requires arguments. – d0001 Dec 19 '14 at 19:54

1 Answers1

2

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.

guest
  • 6,450
  • 30
  • 44
  • Currently my properties are defined as you defined owner not in the Prototype. It does look like defining the properties in the prototype is the only way to go. I will mark this as answer unless anyone else find a way to actually check on the type. – d0001 Dec 19 '14 at 19:56