Search code examples
javascriptparametersobject-type

Pass the true type as a parameter to a method in JavaScript


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;
}

Solution

  • Well, there is an issue with instanceof, it wont work with primitives (see How do I get the name of an object's type in JavaScript?)

    The thing with objects is much better you should just pass Person without "

    var personObjects = getObjectsOfType( allObjects, Person);