I am trying to assign a constructor in a self-executing function in NodeJS. I am sure that it does not work because my parameter is a variable pointing to module.exports, but I am curious if there is a way to make it work as close as possible to a self-executing format.
Here, how the code is called ...
var TemplateEngine = require('./templateEngine'); templateEngine = new TemplateEngine({engine: 'swig'});
Here is a sample code that works great ...
var assert = require('assert'); var swig = require('swig'); // Constructor var TemplateEngine = function(args) { assert.ok(args.engine, 'engine is required'); var templateEngine = {}; templateEngine.engine = args.engine; templateEngine.Render = function(templateString, model) { var result = swig.render(templateString, model); return result; }; return templateEngine; }; module.exports = TemplateEngine;
and here is an example of a code style that I would like to use, but which raises the error “TypeError: Object is not a function”, because I actually do not assign module.exports, just a variable that copied it all pointed to.
(function(templateEngine) { var assert = require('assert'); var swig = require('swig'); templateEngine = function(args) { assert.ok(args.engine, 'engine is required'); var templateEngine = {}; templateEngine.engine = args.engine; templateEngine.Render = function (templateString, model) { var result = swig.render(templateString, model); return result; }; return templateEngine; }; })(module.exports);
Is there a way to use the above self-signed format and my module exports the constructor?
source share