Bin
Bin

Reputation: 484

The function `this` doesn't work in module of nodejs

I create a module with following

module.exports = {
    GetRandomNum:(Min,Max)=>{
        var Range = Max - Min;   
        var Rand = Math.random();   
        return(Min + Math.round(Rand * Range)); 
    },
    mathCalculationtion:()=>{
        var firstPlace = this.GetRandomNum(1, 9);
        return firstPlace;
    }
}

I run this above code and get an error at the line var firstPlace = this.GetRandomNum(1, 9);

at Object. mathCalculationtion (/home/sfud/projectland/lib/comlib.js)

Please help me, thank you.

Upvotes: 1

Views: 442

Answers (3)

Andrei
Andrei

Reputation: 410

Use module.exports instead of this:

module.exports = {
    GetRandomNum(Min,Max) {
        var Range = Max - Min;   
        var Rand = Math.random();   
        return(Min + Math.round(Rand * Range)); 
    },
    mathCalculationtion() {
        var firstPlace = module.exports.GetRandomNum(1, 9);
        return firstPlace;
    }
}

It works for me just fine in NodeJs v12.16.1.

Upvotes: 0

dx_over_dt
dx_over_dt

Reputation: 14318

You are using arrow functions. The this variable does exist within regular objects, but arrow functions pull their this from whatever this is when they're declared (unless you bind them, which would be an odd thing to do).

Change your functions to functions and it should work fine.

module.exports = {
    GetRandomNum(Min,Max) {
        var Range = Max - Min;   
        var Rand = Math.random();   
        return(Min + Math.round(Rand * Range)); 
    },
    mathCalculationtion() {
        var firstPlace = this.GetRandomNum(1, 9);
        return firstPlace;
    }
}

Note: To use it this way, you will need to import the module and call the function with the . syntax.

// This will work
const myModule = require('./my-module');

console.log(myModule.mathCalculationtion());

// This will not work
const { mathCalculationtion } = require('./my-module');

console.log(mathCalculationtion());

This is because this within the function is whatever the x in x.myFunc() is. If you just call myFunc() directly, it has no idea which object to apply it to. If you want to get around this, either define your functions in your module separately and reference them by name in the module, then export each function, or you can use .bind().

Upvotes: 4

White Link
White Link

Reputation: 106

Change this.GetRandomNum(1, 9) to module.exports.GetRandomNum(1, 9) or

declare your functions outside of the module.exports block:

    var getRandomNum = (Min,Max) => {
        var Range = Max - Min;   
        var Rand = Math.random();   
        return(Min + Math.round(Rand * Range)); 
    }
    var mathCalculationtion = () => {
        var firstPlace = getRandomNum(1, 9);
        return firstPlace;
    }

then:

    module.exports = {
        getRandomNum,
        mathCalculationtion
    }

Upvotes: 1

Related Questions