0

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?

1
  • Is the module going to export more than Router? It probably shouldn't (SRP), so you could just have module.exports = Router; Commented Aug 14, 2013 at 20:46

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Dohh... what an idiot mistake. Too late for coding tonight. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.