简体   繁体   English

我可以以原型方式在Node.js中使用require()吗?

[英]Can I use require() in Node.js in a prototypical way?

I've been interested in prototypical programming with JavaScript, and I'm trying to figure out an efficient way of doing it with Node modules. 我一直对使用JavaScript进行原型编程感兴趣,并且我正在尝试找到一种使用Node模块进行建模的有效方法。

For example, I'd like to use a prototype to quickly create a debug object in each of my modules, which has a name property and a log method, constructed via: 例如,我想使用一个原型在我的每个模块中快速创建一个debug对象,该对象具有一个name属性和一个log方法,通过以下方式构造:

custom_modules/debug.js 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);

        }

    }

}

So I'd like to know if I can use that module as a constructor, like so: 所以我想知道是否可以将该模块用作构造函数,如下所示:

do_something.js do_something.js

var debug = new require('custom_modules/debug')("Something Doer");

debug.log("Initialized"); // -> [Debug][Something Doer] : Initialized

Will it work? 能行吗 If not, what's the correct equivalent? 如果不是,什么是正确的等价物?

new doesn't care where the function comes from. new不在乎函数的来源。 So yes, the function can be the result of require ing a module. 所以是的,该功能可能是require模块的结果。

However, the module must directly export the function. 但是,模块必须直接导出功能。 In your current code you are merely assigning a new value to the local exports variable, and we all know that assigning to a local variable doesn't have any effect outside of its scope. 在您当前的代码中,您只是为本地 exports变量分配了一个新值,并且我们都知道分配给本地变量不会超出其范围。

The module will still export an empty object. 该模块仍将导出一个空对象。 You have to override the exports property of the module : 您必须重写moduleexports属性:

module.exports = function() {...};

As pointed out, there will be problems with precedence, so you would have to do 如前所述,优先级会有问题,因此您必须

var debug = new (require('custom_modules/debug'))("Something Doer");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM