替换匿名功能,同时将所有其他功能保留在模块之外
Replacing anonynomous function while keeping all others from module
我对node.js
、prototypical inheritance
和CommonJS
模块模式相当陌生。也许这个问题被回答了一百万次,但我找不到它,所以即使是答案的链接也被认为是答案。
我必须包装一个同时具有命名和未命名函数的模块,如下所示:
// 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);
};
所以这为我们解决了问题,但不是原来的问题。
- 在iPad Web App上拖放 - 同时保留滚动功能
- 删除滚动条,但保留滚动功能
- 使用onkeypress/onkeydown返回自然语言字符,同时保留退格功能
- 如何禁用滚动但保留使用锚链接滚动的功能
- 阻止子 li 可点击,但保留包含 a 的功能
- 如何在保留 JavaScript 调试器功能的同时进行优雅的异常处理
- 如果我创建右键单击菜单,如何保留原始复制和粘贴功能
- 我是否可以在 Bootstrap 3 中为折叠手风琴指定一个相对的“数据目标”,同时保留“折叠其他”功能
- 如何使用ImageButtons在GridView TemplateField中保留图像超链接的样式/悬停功能
- 将表单从选择下拉字段更改为单选按钮并保留功能
- 如何隐藏网页滚动保留滚动功能
- 在移动中添加按钮时保留jQuery功能
- 当onClick功能激活时,保留按钮可见
- 实现漂亮的滚动条,并保留本地功能
- 在不加载页面的情况下保留后退按钮功能
- 如何保留IFrame的功能
- 如何在鼠标退出功能完成后使切换的标题保留
- 替换匿名功能,同时将所有其他功能保留在模块之外
- 为什么可以'是否将函数分配给变量并保留其功能
- 使用 .replacewith 更改图像,但保留 id.之后,图像不再在悬停时触发功能