我在JavaScript中有以下代码,其目的是返回与为参数objectType
传入的类型匹配的所有对象。我尝试为Person
或Employee
之类的objectType传递字符串,但随后instanceof
运算符引发错误,提示expecting a function in instanceof check
。
问题:在下面的方法中,将JavaScript中的对象类型作为参数传递的正确方法是什么?以下网址的此代码演示不起作用: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?)
带有物体的东西要好得多,您应该通过不带“
var personObjects = getObjectsOfType( allObjects, Person);
关于javascript - 将真实类型作为参数传递给JavaScript中的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34374338/