Mahmoud Niypoo
Mahmoud Niypoo

Reputation: 1710

call function from same class nodejs

I try to call function from same class but it always return an error TypeError: this.c is not a function I tried also module.exports.c() and the same result

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

After Updated

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

Upvotes: 0

Views: 452

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53874

You can try and export a class, just pass options to your 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);

Upvotes: 0

NullDev
NullDev

Reputation: 7303

Arrow functions bind this lexically (meaning it does not bind it's own this).
Use normal function expressions instead:

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

Browserfied example:

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

Upvotes: 2

Related Questions