Reputation: 10067
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?
Upvotes: 0
Views: 516
Reputation: 887937
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();
Upvotes: 3