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

How to extend javascript module which use prototype

在我的项目中有一个模块是在特定的 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方法,例如我想向其中添加地址数据,可以吗??? 如果是的话我应该怎么做? 例子会很有帮助!

提前致谢!

如果您只想为一个实例更改此方法,您可以做的是在您的模块中创建一个新的 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);
}

这样的东西行得通吗?

//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
  }
}())