gpt4 book ai didi

javascript - Node js 在 module.exports 中使用函数调用中的 "this"

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:38 27 4
gpt4 key购买 nike

我正在从 module.exports 函数中调用本地函数。如何访问 exports this 对象?

exports.myVar = 'foo'

exports.myFunc = function() {
localFunc()
}

function localFunc() {
console.log(this.myVar) //Undefined
}

我尝试过使用 localFunc().bind(this) 但这也不起作用。如有任何帮助,我们将不胜感激!

最佳答案

有两种方法可以解决您的问题。

第一个:

exports.myVar = 'foo'

exports.myFunc = function() {
that = this;
localFunc(that)
}
function localFunc(that) {
console.log(that.myVar) //foo
}

第二个

exports.myVar = 'foo'

exports.myFunc = function() {
localFunc()
}

localFunc = ()=> {
console.log(this.myVar) //foo
}

关于javascript - Node js 在 module.exports 中使用函数调用中的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808157/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com