如何从需要代码的Augument commonjs模块?

时间:2015-07-01 12:20:16

标签: javascript prototype commonjs

我想知道如何从另一个需要它的模块中扩展一个commonjs模块。

我们假设我有三个文件,两个commonjs模块如下:

my-example-module.js

function MyExampleModule(){}

MyExampleModule.prototype = {

    bindings: {
        some: 'random',
        prop: 'values'
    }

}

module.exports = MyExampleModule;

另一个-示例-module.js

var MyExampleModule = require('./my-example-module');

function AnotherExampleModule(){}

AnotherExampleModule.prototype = {

    getMyExampleModuleBindings: function(){
        var module = new MyExampleModule();
        return module.bindings;
    }

}

module.exports = AnotherExampleModule;

app.js

var MyExampleModule = require('./my-example-module');
var AnotherExampleModule = require('./another-example-module');

//modify?!?

var anotherExampleModule = new AnotherExampleModule();
console.log(anotherExampleModule.getMyExampleModuleBindings());

所以我想做的是让//modify?!?成为某种代码,它会改变原始的MyExampleModule原型,所以当其他任何尝试require MyExampleModule时,它都会得到修改后的版本

一个具体的问题是 - 我应该用//modify?!?替换什么,所以我在假设my-example-module.js是只读的情况下登出控制台。

{
    some: 'random',
    prop: 'values',
    added: 'binding'
}

1 个答案:

答案 0 :(得分:1)

如果你想在nodejs / iojs中这样做,这很简单。当节点导入CommonJS模块时(让它调用它A),它会创建一个内部对象。

当另一个模块(B)想要加载相同的模块(A)时,它只获取对该内部对象的引用。因此,如果您更改了MyExampleModuleapp.js上的内容,它也会应用于MyExampleModule中的another-example-module.js

app.js

var MyExampleModule = require('./my-example-module');
var AnotherExampleModule = require('./another-example-module');

//modify:

MyExampleModule.prototype.bindings = {
    some: 'random',
    prop: 'values',
    added: 'binding'
};

var anotherExampleModule = new AnotherExampleModule();
console.log(anotherExampleModule.getMyExampleModuleBindings());

由于您在{/ 1>之后在MyExampleModule 中创建another-example-module.js的新实例,因此在MyExampleModule.prototype.bindings = {...}中调用app.js,新实例将已创建修改后的.prototype

虽然我还没有在浏览器中对此进行过测试,但它确实适用于CommonJS的webpacks实现。

查看runnable上的工作示例( app.js 名为 server.js ): http://code.runnable.com/VZPdN5k65gE5vUIz