I've got a module that looks like this:
var MyModule = module.exports = function MyModule(opts) {
opts = (opts === Object(opts)) ? opts : {};
if (!(this instanceof MyModule)) {
return new MyModule(opts);
}
for (var key in opts) if ({}.hasOwnProperty.call(opts, key)) {
this.config[key] == opts[key];
}
};
MyModule.prototype.config = {
something:'value'
}
MyModule.prototype.put = function put(info, cb) {
//do stuff
};
However, when I use it like this:
var myModule = require('myModule.js');
myModule.put({test}, function(){
//some callback stuff
});
I get the following error:
TypeError: Object function MyModule(opts) {
opts = (opts === Object(opts)) ? opts : {}; if (!(this instanceof MyModule)) { return new MyModule(opts); } for (var key in opts) if ({}.hasOwnProperty.call(opts, key)) { this.config[key] == opts[key]; } } has no method 'put'
It appears I have something wrong with my MyModule.prototype.put
?
You wrote :
var myModule = require('myModule.js');
myModule.put({}, function(){
//some callback stuff
});
Here myModule
is in fact MyModule
, a constructor function. So what you are doing is MyModule.put()
, a call to a "static" method of MyModule
. MyModule.prototype.put
defines an "instance" method so you have to instanciate first :
var MyModule = require('./myModule.js');
var myModule = new MyModule();
// or as you used `if (!(this instanceof MyModule)) { … }`
var myModule = MyModule();
myModule.put({}, function () {});
So basically your code needs just a pair of ()
to work :
MyModule().put({}, function () {});
// same as
(new MyModule).put({}, function () {});
Récap :
var MyModule = function () {
// Construct object
};
MyModule.staticMethod = function () {
this; // is bound to `MyModule` function object
};
MyModule.prototype.instanceMethod = function () {
this; // is bound to the `MyModule` instance object it’s called from
};
// Usage
MyModule.staticMethod();
var instance = new MyModule();
instance.instanceMethod();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With