0

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');
        }
    }
}
1
  • It's not a Class it's an Object (no this) Commented Apr 13, 2019 at 19:12

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@MahmoudNiypoo Update your code, like what you tried so that we can help you in fixing it
@MahmoudNiypoo The second code you added is invalid. Working example here.
0

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

3 Comments

I need to pass options to InnerCall(options)
No problem, use constructor (I edited the answer)
thanks Dennis your code work fine but when I have wrote it , show up TypeError: Cannot read property 'c' of undefined this error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.