gpt4 book ai didi

javascript - 如何从需要的代码中增强 commonjs 模块?

转载 作者:行者123 更新时间:2023-12-03 09:41:50 27 4
gpt4 key购买 nike

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

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

<小时/>

my-example-module.js

function MyExampleModule(){}

MyExampleModule.prototype = {

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

}

module.exports = MyExampleModule;
<小时/>

another-example-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 原型(prototype),这样当其他任何东西尝试 require MyExampleModule 它将获取修改后的版本。

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

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

最佳答案

如果你想在nodejs/iojs中执行此操作,这非常简单。当节点导入 CommonJS 模块(我们称之为 A)时,它会创建一个内部对象。

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

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());

由于您在调用 MyExampleModule.prototype 之后,在 another-example-module.js 中创建了 MyExampleModule 的新实例。。在 app.js 中,bounds = {...} 已使用修改后的 .prototype 创建新实例。

虽然我还没有在 browserify 中测试过这一点,但它当然也适用于 CommonJS 的 webpacks 实现。

查看可运行的工作示例(app.js 称为 server.js): http://code.runnable.com/VZPdN5k65gE5vUIz

关于javascript - 如何从需要的代码中增强 commonjs 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com