从同一类nodejs调用函数

时间:2019-04-13 19:08:31

标签: node.js express

我尝试从同一个类调用函数,但是它总是返回错误TypeError: this.c is not a function,我也尝试了module.exports.c()和相同的结果

module.exports = (options)=>{
    return{
        a:(a)=>{
           console.log(a);
        },
        b:(b)=>{
          this.c('c');
          console.log(b)
        },
        c:(c)=>{
           console.log(c);
        }
    }
}

更新后

module.exports =  ({})=>{
    return{
        genereate:function(identifier){
            console.log('genereate')
        },
        middleware:function(req,res,next){
            this.c();
            console.log('genereate')
        },
        c:function(){
            console.log('geeet');
        }
    }
}

2 个答案:

答案 0 :(得分:2)

箭头功能bind this lexically(意味着它不绑定自己的this)。
改用普通的函数表达式:

module.exports = (options) => {
    return {
        a: function(a){
            console.log(a);
        },
        b: function(b){
            this.c('c');
            console.log(b)
        },
        c: function(c){
            console.log(c);
        }
    };
};

浏览示例:

let f = (options) => {
    return {
        a: function(a){
            console.log(a);
        },
        b: function(b){
            this.c('c');
            console.log(b)
        },
        c: function(c){
            console.log(c);
        }
    };
};

f().a("a");
f().b("b");
f().c("c");

答案 1 :(得分:0)

您可以尝试导出class,只需将options传递到您的constructor

class InnerCall {
  constructor(options) {
    this.options = options;
  }

  a(a) {
    console.log(a);
  }

  b(b) {
    this.c('c');
    console.log(b);
  }

  c(c) {
    console.log(c);
  }
}

const example = new InnerCall({ option: 'Im an option' });

example.b('check this out');
console.log(example.options.option);