Question

I have a simple module, it's code

    var Router = function(pattern) {
        this.setRoutePattern(pattern);
    };

    Router.prototype = {
        setRoutePattern: function(){
           this._pattern = pattern || "controller/action/id";
        }
    };

    module.exports.router = Router;

then in my other file I want to use router and have the following code:

var router = require('./../routing').router();

But this line of code fail with no method exception

Object #<Object> has no method 'setRoutePattern'

Why this happened, why prototype methods do not visible in constructor if I load code with require function?

Was it helpful?

Solution

You're trying to instantiate your class (so that it gets a this and its prototype).
To do that, you need the new keyword.

However, you can't combine that directly with require; otherwise, it will be parsed as

(new require('./../routing').router()

(calling require() as a constructor)

Instead, you need to wrap the entire function expression in parentheses:

new (require('./../routing').router)()

Or, better yet,

var Router = require('./../routing').router;
var router = new Router();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top