简体   繁体   中英

Node JS Module, How can I use local function in module

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM