I have following code in JavaScript in which my goal is to return all objects that match the type passed in for the parameter objectType
. I tried passing a string for objectType like Person
or Employee
, but then the instanceof
operator throws an error saying expecting a function in instanceof check
.
Question: What would the right way of passing object type in JavaScript as a parameter in below method? A demo of this code that is not working is at following URL: demo of this
function getObjectsOfType(allObjects, objectType) {
var objects = [];
for (var i = 0; i < allObjects.length; i++) {
if (allObjects[i] instanceof objectType) {
objects.push(allObjects[i]);
}
}
return objects;
}
//CALL to ABOVE Method which throws an error
var personObjects = getObjectsOfType( allObjects, "Person");
var employeeObjects = getObjectsOfType( allObjects, "Employee");
//Person object constructor
function Person(fullname, age, city) {
this.fullName = fullname;
this.age = age;
this.city = city;
}
//Employee object constructor
function Employee(fullname, age, position, company) {
this.fullName = fullname;
this.age = age;
this.position = position;
this.company = company;
}