替换匿名功能,同时将所有其他功能保留在模块之外

Replacing anonynomous function while keeping all others from module

本文关键字:功能 保留 其他 模块 替换      更新时间:2023-09-26

我对node.jsprototypical inheritanceCommonJS模块模式相当陌生。也许这个问题被回答了一百万次,但我找不到它,所以即使是答案的链接也被认为是答案。

我必须包装一个同时具有命名和未命名函数的模块,如下所示:

// a.js
function a(data) {
    console.log(data, 'A')
}
function b() {
     a('B');
 }
module.exports = a;
module.exports.b = b;

鉴于 OOP 背景,我想以某种方式"继承">模块的所有功能,同时我想覆盖匿名函数(我想向数据添加一些字段(。

非常重要的是,在新模块中重写function a后,function b应使用重写的方法而不是原始方法。

// 'inherited.js'
var a = require('./a');
function overriddenA(data) {
    data.myAddedValue = 'an important addition';
    a(data);
}    
// I would like to export all other functions and properties of the original module
[magic that overrides the anonymous function while keeping all other functions as they are]

从我使用它的地方,它应该看起来像这样:

var decoratedA = require('./inherited');
decoratedA('stuff'); // it calls overridden function
decoratedA.b();      // it calls the original a.b() which in turn calls the overridden function

解决了我们原来的问题

看看这个: https://stackoverflow.com/a/31459267/2018771 - 如果你对抽象问题有任何评论,请回答这个问题。我们很好奇:)。

我想

以某种方式"继承"模块的所有功能,同时我想覆盖匿名函数

想使用一些黑魔法吗?那么__proto__是要走的路:

var a = require('./a');
function overriddenA(data) {
    data.myAddedValue = 'an important addition';
    a(data);
}    
overriddenA.__proto__ = a;
module.exports = overriddenA;

没有实际继承的更干净的方法是将所有属性从a复制到overriddenA。您可以使用Object.assign(或垫片(、_.extend或简单的for in循环。

同时,

我们已经解决了我们最初的问题,即为库的每个调用添加一个特殊的标头request。在该实现中,有像get()put()post()等函数使用一个函数:function request(...)被导出module.exports = request

我的理解是,我必须用我们自己的request(...)替换该,添加我们的标头,然后调用原始函数。

但我们很幸运,因为request(...)返回了一个我们可以根据需要修改的对象:

Request.prototype.__originalInit = Request.prototype.init;
requestPromise.Request.prototype.init = function(options){
    console.log('adding our stuff');
    this.__originalInit(options);
};

所以这为我们解决了问题,但不是原来的问题。