[英]Overriding method in node.js
i'm looking for the best way to overrid a method in a custom module node.js. 我正在寻找最好的方法来覆盖自定义模块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? 我的方法好吗?
Thanks for reading. 谢谢阅读。 Tom 汤姆
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;
Then you can use this like this: 然后您可以像这样使用:
// MAIN APP EXAMPLE
// ========================================
var myCustomModule = require('customModule.js');
var loader = myCustomModule({
method: function() {
return "viewer" + myCustomModule.DEFAULT_SUFFIX;
}
});
loader.loadModule();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.