Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何扩展使用prototype的javascript模块_Javascript_Jquery_Module_Requirejs - Fatal编程技术网

如何扩展使用prototype的javascript模块

如何扩展使用prototype的javascript模块,javascript,jquery,module,requirejs,Javascript,Jquery,Module,Requirejs,在我的项目中,有一个模块是在特定的JS文件中实现的,如下面的示例所示 define("Company", ["exports", "Employee"], function(Employee) { function Company(name) { this.name = name; this.employees = []; }; Company.prototype.addEmployee = function(name) {

在我的项目中,有一个模块是在特定的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方法,例如我想向其中添加地址数据,是否可能??? 如果是,我应该怎么做? 示例将非常有用


提前谢谢

如果您只想为一个实例更改此方法,您可以做的是在模块中创建
公司
的新实例,通过添加您自己的代码来覆盖实例上的
addEmployee
方法,然后从prototype调用原始方法:

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

为什么要在不同的模块中进行此操作?当您在不同的地方有不同的定义时,从维护的角度来看,这是非常困难的。@Magrangs谢谢,但有一个模块具有特定用例的基本功能(此文件包含近2000行代码…:)而不是我的…)现在我想使用其中一些方法来实现一些基本功能并扩展它以支持新版本,我的问题是我应该如何正确和干净地完成它…问题是你不能仅仅替换功能,因为它会影响使用公司模块的所有内容。@Magrangs-什么意思会影响所有内容?您还推荐使用另一种解决方案,它非常优雅…?请查看@Zemljoradnik的答案(他在我有机会之前回答:))谢谢!你的意思是这样的吗?。我尝试了一下,但它不起作用……我错过了什么吗?@JhonDree你原来的addEmployee没有返回任何内容,因此你可以返回员工的原件或使用此.employees[this.employees.length-1]要设置地址,谢谢,我尝试了一下,但它对我不起作用。我错过了什么吗?您正在尝试在JSFIDLE中使用require.js,我甚至不确定这是否可行。您正在创建一个新的
员工
,但没有定义
员工
新公司
必须是
新公司
@Zemljoradnik让我们假设我克服了需求问题,我在jsFiddle中做错了什么?你能修好并分享吗?提前谢谢!例如,如果要将地址添加到员工:。