繁体   English   中英

function `this` 在 nodejs 的模块中不起作用

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

我创建了一个具有以下内容的模块

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

我运行上面的代码并在var firstPlace = this.GetRandomNum(1, 9);

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

请帮帮我,谢谢。

您正在使用箭头函数。 this变量确实存在于常规对象中,但是箭头函数在声明它们时从this中提取它们(除非你绑定它们, this将是一件奇怪的事情)。

将您的功能更改为function ,它应该可以正常工作。

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

注意:要以这种方式使用它,您需要导入模块并使用. 句法。

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

console.log(myModule.mathCalculationtion());

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

console.log(mathCalculationtion());

这是因为 function 中的thisx.myFunc()中的x 如果您只是直接调用myFunc() ,它不知道将其应用于哪个 object。 如果你想解决这个问题,要么在你的模块中单独定义你的函数并在模块中按名称引用它们,然后导出每个 function,或者你可以使用.bind()

this.GetRandomNum(1, 9)更改为module.exports.GetRandomNum(1, 9)

module.exports块之外声明你的函数:

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

然后:

    module.exports = {
        getRandomNum,
        mathCalculationtion
    }

使用module.exports而不是这个

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

它在 NodeJs v12.16.1 中对我很有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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