如何扩展使用原型的javascript模块

时间:2015-03-17 09:15:11

标签: javascript jquery module requirejs

有一个模块在我的项目中的特定JS文件中实现,如下例

define("Company", ["exports", "Employee"], function(Employee) {
    function Company(name) {
        this.name = name;
        this.employees = [];
    };
    Company.prototype.addEmployee = function(name) {
        var employee = new Employee.Employee(name);
        this.employees.push(employee);
        employee.company = this;
    };
    exports.Company = Company;
});

现在在不同的JS文件(新模块)中我想扩展 addEmployee 方法,例如我想向它添加地址数据,是否可能? 如果是的话我应该怎么做? 示例将非常有用!

提前致谢!

2 个答案:

答案 0 :(得分:1)

如果您只想为一个实例更改此方法,那么您可以在模块中创建Company的新实例,通过添加您自己的代码覆盖实例上的addEmployee方法,而不是从原型中调用原始方法:

// create a new instance of Company
var myCompany = new Company('myCompany');
// add method 'addEmployee' to your instance, it will override original method
// you can, of course, add more arguments if you wish
myCompany.addEmployee = function(name) {
    // your code here
    // and than call the original method settings it's 'this' to 'this' of your instance, 
    // and providing appropriate arguments
    Company.prototype.addEmployee.call(this, name);
}

答案 1 :(得分:0)

这样的事情有用吗?

//required as Company
(function(){
  var addEmployee = Company.prototype.addEmployee;
  Company.prototype.addEmployee = function(name, address){
    //assuming the original addEmployee returns the created instance
    var emp = addEmployee.call(this,name);
    //do something with address
    emp.address=address;
    return emp;//also return the created employee so it'll behave the same as the original
  }
}())