file.js

module.exports = (function(){ var _num; this.Test = function(){ // ... }; this.Test.prototype = { setNum: function(n){ _num = n }, getNum: function(){ return _num } } })() 

main.js

 var Test = require('path.file.js'); var test = new Test(); // так не работает. // Вопрос: как правильно подключать анонимную функцию? 
  • What does not work? In your case, this is something like new (new Test ()). Test - zb '27

1 answer 1

If you really want an anonymous letter (it is not clear why), it is done like this:

 module.exports=function(){ this.var=1; this.test=function() { console.log(this.var); } this.testAdd=function(a) { a=parseInt(a)||0; return this.var+=a; } }; 

well done like this:

 module.exports=Test; function Test(){}; Test.prototype.var=1; Test.prototype.test=function() { console.log(this.var); } Test.prototype.testAdd=function(a) { a=parseInt(a)||0; return this.var+=a; } 
  • @eicto, thanks! Apparently, by the night I was already tired and asked, being in a semi-delirious :) I wanted to create an anonymous function to facilitate access to private properties, but forgot that this is not necessary, since the module is considered as an object. - vas
  • @vas, be careful with "private" properties, because The external scope of two instances of the same object is the same. - zb '
  • those. This has a very limited use of module.exports = Test; var n = 0; function Test () {}; Test.prototype.test = function () {console.log (n); } Test.prototype.testAdd = function (a) {a = parseInt (a) || 0; return n + = a; } - zb '
  • @eicto, that's why I returned to the anonymous function, but then I checked and it turned out that you can do var prop = value with modules and then the two instances have different prop properties. - vas
  • Test = require ("./ test.js"); var test1 = new Test, test2 = new Test; test1.testAdd (2); test2.test (); // 2 - zb '