node.js 中的覆盖方法 [英] Overriding method in node.js
问题描述
我正在寻找覆盖自定义模块 node.js 中方法的最佳方法.
i'm looking for the best way to overrid a method in a custom module node.js.
我正在开发一个自定义中间件,它将帮助我自动加载一些自定义模块.像安全,用户等...
I'm working on a custom middleware who will help me to automatically load some custom module. Like security, users etc...
但如果我需要自定义安全检查之类的东西,我希望能够覆盖某些方法.目前我发现的唯一方法是导出一个函数,该函数将替换我的方法并公开上下文变量.
But i want to be able to override some methods if i need something like a custom security hand check. For now the only way i found is to export a function who will replace my method and expose context variables.
// CUSTOM MODULE EXAMPLE
// ========================================
var myVar = "Hello ";
var myVar2 = "!";
var method = function() {
return "world" + myVar2;
}
module.exports.loadModule = function() {
console.log(myVar + method());
};
module.exports.overrideMethod = function(customMethod) {
method = customMethod;
};
module.exports.myVar2 = myVar2;
我的主应用程序将是这样的:
And my main app will be like that:
// MAIN APP EXAMPLE
// ========================================
var myCustomModule = require('customModule.js');
myCustomModule.overrideMethod(function() {
return "viewer" + myCustomModule.myVar2;
});
myCustomModule.loadModule();
你怎么看?我走得好吗?
What do you think? Am i on the good way?
感谢阅读.汤姆
推荐答案
通常,我将任何具有可变全局状态的模块视为错误.相反,我会选择使用这些方法创建一个对象并有一种方法来传递覆盖.
Generally I treat any module that has mutable global state like this to be a mistake. Instead, I'd opt for creating an object with these methods and having a way to pass in overrides.
// CUSTOM MODULE EXAMPLE
// ========================================
var DEFAULT_PREFIX = "Hello ";
var DEFAULT_SUFFIX = "!";
var DEFAULT_METHOD = function() {
return "world" + DEFAULT_SUFFIX;
};
module.exports = function(options){
var method = options.method || DEFAULT_METHOD
return {
loadModule: function(){
console.log(myVar + method());
}
};
};
module.exports.DEFAULT_SUFFIX = DEFAULT_SUFFIX;
然后你可以这样使用:
// MAIN APP EXAMPLE
// ========================================
var myCustomModule = require('customModule.js');
var loader = myCustomModule({
method: function() {
return "viewer" + myCustomModule.DEFAULT_SUFFIX;
}
});
loader.loadModule();
这篇关于node.js 中的覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!