Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Module exports / prototype - has no method

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 ?

like image 657
Alex Avatar asked Jan 13 '13 03:01

Alex


1 Answers

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();
like image 170
kevin Avatar answered Oct 11 '22 00:10

kevin