0

I'm wondering how can I access local function in my module.

In calc module :

var calc = {};
calc.add = function(a,b){
    return a+b;
};

calc.multi = function(a,b){
    return a*b;
};

module.exports = calc;

However If I add some function use a local function like this :

calc.verify = function(a,b){
    return (this.add(a,b)) + (this.multi(a,b))
};

This is not working properly. I'd like to use both calc.add and calc.multi function at any time in my module.

What's wrong in my code?

Edit ::

var calc = {};
calc.add = function(a,b){
    return a+b;
};

calc.multi = function(a,b){
    return a*b;
};

calc.verify = function(a,b){
    return (this.add(a,b)) + (this.multi(a,b))
};

module.exports = calc;
2
  • 2
    Depending on how verify is called, this might not be the calc object. Try s/this/calc/ Commented Mar 15, 2018 at 5:29
  • How are you requiring the module and calling verify()? A sample code of that would help. Commented Mar 15, 2018 at 5:45

1 Answer 1

1

It depends on how you are calling verify().

Supposing your module is called calc.js, this should work:

const calc = require('./calc');
console.log(calc.verify(1,2));

This does not work:

const calc = require('./calc');
const verify = calc.verify;
console.log(verify(1,2));

Nor this:

const { verify } = require('./calc')
console.log(verify(1, 2));

The reason is that if you call verify() as an unbound function, this will become undefined. If for some reason you want to call verify() as an unbound function, you can use bind():

const calc = require('./calc');
const verify = calc.verify.bind(calc);
console.log(verify(1,2));

Other way would be rewriting your calc.js module without using this:

calc.verify = function(a,b){
    return (calc.add(a,b)) + (calc.multi(a,b))
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Perfect!! :)

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.