I have the JavaScript snippet below. Simply put, what am trying to achieve is; A way to check if a parameter passed to a function is an instance of some predetermined classes. I know I can use
if(obj instanceof className){ /* do stuff * / } else{ /* other things */ }statements but it would be bulky code, especially if I have a bunch of classes to test against. To cut the story short, how can I achieve what am trying to do with the code below? Thanks all.
class A {
constructor(name) {
this._name = name;
}
}
class B {
constructor(name) {
this._name = name;
}
}
class C {
constructor(name) {
this._name = name;
}
}
let allTemplates = ['A', 'B', 'C', 'Object']; //available classes
let a = new A('A class');
let b = new B('B class');
let c = new C('C class');
function seekTemplateOf(obj) {
/**find if @arg obj is an instance of any
** of the classes above or just an object
**@return string "class that obj is instance of"
**/
return allTemplates.find(function(template) {
return obj instanceof window[template];
/*Thought that ^^ could do the trick?*/
});
}
console.log(seekTemplateOf(a));
/*"^^ Uncaught TypeError: Right-hand side of 'instanceof' is not an object"*/