NodeJS模块导出/原型 - 没有方法 [英] NodeJS Module exports / prototype - has no method

查看:171
本文介绍了NodeJS模块导出/原型 - 没有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的模块:

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
});

我收到以下错误:


TypeError:对象函数MyModule(opts){

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'


它我的 MyModule.prototype.put 出现了问题?

推荐答案

你写道:

var myModule = require('myModule.js');

myModule.put({}, function(){
  //some callback stuff
});

这里 myModule 实际上是 MyModule ,一个构造函数。所以你要做的是 MyModule.put(),调用 MyModule 的静态方法。 MyModule.prototype.put 定义了一个实例方法,因此您必须先实例化:

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();

这篇关于NodeJS模块导出/原型 - 没有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆