如何一次调用同一构造函数中的所有对象?

时间:2015-02-09 00:50:36

标签: javascript object methods prototype

我是javascript的新手。我想一次过滤所有Employee对象,并返回等于或超过300薪水的名称。然后我想将这些结果存储到一个数组中。我不知道如何在所有对象上调用方法filterSalaries()。请帮帮我。

var EmployeeBlueprint = {

    all_info: function () {
        console.log("Employee: " + this.name + " has a salary of $" + this.salary + ".");
    },
    isMale: function() { return this.gender == "Male"; },
    isFemale: function() { return this.gender == "Female"; },

    filterSalaries: function() {
        if (this.salary >= 300) {
            return this.name;
        }
    }
};

function Employee (name, salary, gender) {
    this.name = name;
    this.salary = salary;
    this.gender = gender;
};

Employee.prototype = EmployeeBlueprint;

var Matt = new Employee("Matt", 100, "Male");
var Alex = new Employee("Alex", 200, "Male");
var Zack = new Employee("Zack", 300, "Male");
var Mark = new Employee("Mark", 400, "Male");
var Rick = new Employee("Rick", 500, "Male");

1 个答案:

答案 0 :(得分:1)

摆脱这些变量并将它们存储在一个数组中。

var emps = [
   new Employee("Matt", 100, "Male"),
   new Employee("Alex", 200, "Male"),
   new Employee("Zack", 300, "Male"),
   new Employee("Mark", 400, "Male"),
   new Employee("Rick", 500, "Male")
];

然后.filter()数组得到你的简化集和.map()设置名称。

var low_salary_names = emps.filter(function(emp) {
    return emp.salary <= 300;
}).map(function(emp) {
    return emp.name;
});