0

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;
}
Sunil
  • 20,653
  • 28
  • 112
  • 197

1 Answers1

1

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);
Community
  • 1
  • 1
Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141
  • Ok. I will try it out. I have also just posted a demo at this URL: http://js.do/sun21170/77402 – Sunil Dec 19 '15 at 19:27
  • Yes that works. Brilliant. I get it. So one must always pass the type name without enclosing it in quotes when passing the type as a parameter. – Sunil Dec 19 '15 at 19:28