java 脚本 如何访问同一模块中的函数,当它不指向模块而是指向全局范围时

java script how to access function within the same module when this doesn't point to the module instead points to the global scope

提问人:mumboFromAvnotaklu 提问时间:1/11/2022 更新时间:1/12/2022 访问量:38

问:

以这种方式调用模块中的函数时

app.get("/api/sessions/oauth/google", (req, res) => {
  return google_callback.googleOAuthHandler(req, res);
});

this指向该模块,可以使用以下命令访问模块中的另一个函数this

googleOAuthHandler : async function (req, res) {
  const code = req.query.code.toString();
  const {id_token, access_token} = await this.getGoogleOAuthToken(code);
}

但是,将函数作为参数传递将更改为全局函数并变为未定义 即在做的时候thisthis.getGoogleOAuthToken

app.get("/api/sessions/oauth/google", google_callback.googleOAuthHandler);

使用这种方式时,我将如何访问模块中的内容getGoogleOAuthTokengoogleOAuthHandlergoogle_callback

javascript node.js 模块 这个

评论


答:

0赞 mumboFromAvnotaklu 1/12/2022 #1
app.get("/api/sessions/oauth/google", google_callback.googleOAuthHandler);

以这种方式传递函数并不意味着 .所以行不通。thismodulethis.getGoogleOAuthToken

但是,我们可以用来访问同一模块中的函数。在第一个示例中,使用也有效。module.exports.getGoogleOAuthTokenmodule.exports.getGoogleOAuthToken

或者,如果您不喜欢调用该函数,则可以将 line 放在文件顶部,或者用于调用模块内的函数。module.exportsconst _this = this;const _this = module.exports = { ... }_this.function

也刚刚注意到,在第一个示例中,只有因为我使用了这种语法才有效。this.function

module.exports = {
  func1 : function(){},
  func2 : function(){}
}

导出时

module.exports.func1 = function(){}
module.exports.func2 = function(){}

this不能用于访问其他功能