将真实类型作为参数传递给 JavaScript 中的方法

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

我在 JavaScript 中有以下代码,我的目标是 return 所有与为参数 objectType 传入的类型相匹配的对象。我尝试为 objectType 传递一个字符串,例如 PersonEmployee,但是 instanceof 运算符会抛出一个错误,提示 expecting a function in instanceof check.

问题:将 JavaScript 中的对象类型作为以下方法的参数传递的正确方法是什么?此代码无法正常工作的演示位于以下 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;
}

好吧,instanceof 有一个问题,它不适用于原语(参见 How do I get the name of an object's type in JavaScript?

有对象的东西要好得多,你应该只传递没有 "

的 Person
var personObjects = getObjectsOfType( allObjects, Person);