简体   繁体   English

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

[英]How to extend javascript module which use prototype

there is module which was implemented in specific JS file in my project like the following example 有在我的项目中的特定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;
});

Now In different JS file (new module) I want to extend addEmployee method, for example I want to add address data to it,is it possible??? 现在在不同的JS文件(新模块)中,我想扩展addEmployee方法,例如,我想向其添加地址数据,有可能 if yes how should I do that ? 如果是,我该怎么做? example will be very helpful! 这个例子将非常有帮助!

Thanks in advance! 提前致谢!

If you want to change this method for one instance only what you can do is create a new instance of Company in your module, override addEmployee method on your instance by adding the code of your own, and than call the original method from prototype: 如果只想为一个实例更改此方法,只能在模块中创建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);
}

Does something like this work? 这样的事情行吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM