NodeJS:从同一文件中的另一个函数内部调用函数

问题描述 投票:0回答:1

我有NodeJS程序。

在一堂课中,我有各种实用方法。一个函数safeGithubPush调用safeString,同一类中的另一个函数

module.exports = {

  safeString(stringToCheck) {
    console.log(validator.isAscii(stringToCheck), validator.matches(stringToCheck, /^((\w)*[-.]?(\w)*)*$/))
    return (
      validator.isAscii(stringToCheck) &&
      validator.matches(stringToCheck, /^((\w)*[-.]?(\w)*)*$/)
    );
  },

  safeGithubPush(currentJob) {
    if (
      !currentJob ||
      !currentJob.payload ||
      !currentJob.payload.repoName ||
      !currentJob.payload.repoOwner ||
      !currentJob.payload.branchName
    ) {
      this.logIn(
        currentJob,
        `${'    (sanitize)'.padEnd(15)}failed due to insufficient job definition`
      );
      throw invalidJobDef;
    }

    if (
      this.safeString(currentJob.payload.repoName) &&
      this.safeString(currentJob.payload.repoOwner) &&
      this.safeString(currentJob.payload.branchName)
    ) {
      return true;
    }
    throw invalidJobDef;
  },

} 

虽然this.logIn()是实用程序类中的另一个func,但工作正常,但出现safeString的错误:

Error caught by first catch: TypeError: this.safeString is not a function

我关注了a solution offer by another SO post

safeString: function(stringToCheck){
...
}

safeGithubPush(currentJob) {
...
if (
    this.safeString(currentJob.payload.repoName) &&
    this.safeString(currentJob.payload.repoOwner) &&
    this.safeString(currentJob.payload.branchName)
    ) {
       return true;
   }
}

但是这也得到一个TypeError: this.safeString is not a function

我没有使用箭头功能,它是the explanation for this error on a different SO post

node.js this typeerror
1个回答
0
投票

我将重组此代码。您说这些是实用程序函数,这使我认为您实际上并不需要考虑this来构造它们。

而不是在定义时将它们全部附加到module.exports,而是在外部定义它们并直接引用您要使用的功能,然后将它们附加到exports,以便其他模块可以使用这些功能:

function safeString(stringToCheck) {
  return true;
}

function safeGithubPush(currentJob) {
  if (!safeString("some")) {
    throw new Error("Not safe");
  }
  return true;
}

module.exports = {
  safeString,
  safeGithubPush
};
© www.soinside.com 2019 - 2024. All rights reserved.