[英]Can I use require() in Node.js in a prototypical way?
我一直对使用JavaScript进行原型编程感兴趣,并且我正在尝试找到一种使用Node模块进行建模的有效方法。
例如,我想使用一个原型在我的每个模块中快速创建一个debug
对象,该对象具有一个name
属性和一个log
方法,通过以下方式构造:
custom_modules / debug.js
var settings = require('custom_modules/settings');
exports = function debug(name){
this.name = name;
this.log = function(message){
if (settings.debug == 'true'){
console.log("[Debug][" + name + "]: " + message);
}
}
}
所以我想知道是否可以将该模块用作构造函数,如下所示:
do_something.js
var debug = new require('custom_modules/debug')("Something Doer");
debug.log("Initialized"); // -> [Debug][Something Doer] : Initialized
能行吗 如果不是,什么是正确的等价物?
new
不在乎函数的来源。 所以是的,该功能可能是require
模块的结果。
但是,模块必须直接导出功能。 在您当前的代码中,您只是为本地 exports
变量分配了一个新值,并且我们都知道分配给本地变量不会超出其范围。
该模块仍将导出一个空对象。 您必须重写module
的exports
属性:
module.exports = function() {...};
如前所述,优先级会有问题,因此您必须
var debug = new (require('custom_modules/debug'))("Something Doer");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.