javascript - 声明原型(prototype)并在 NodeJS 中的同一文件中使用它

标签 javascript node.js module-export

我创建了一个具有原型(prototype)的函数,我将在其他文件中使用它。

函数.js

function Graph() {
  //Constructor
  this.Client = null;
}
module.exports = Graph;
Graph.prototype.Init = async function Init() {
      ....
      tokenResult = await GetToken();
};

function GetToken() {
 ...
};

我会在文件外部使用 GetToken 方法。所以我添加了 GetToken 函数作为原型(prototype)

function Graph() {
  //Constructor
  this.Client = null;
}
module.exports = Graph;
Graph.prototype.Init = async function Init() {
      ....
      tokenResult = await GetToken(); <== Error here
};
Graph.prototype.GetToken = function GetToken() {
     ...
};

当我运行程序时,出现此错误:

GetToken is not defined

此外,我还知道如何仅导出 token 的值而不导出函数(以便我可以使用相同的 token )

最佳答案

对于像 Graph.prototype.GetToken = function GetToken() 这样的函数表达式,名称 GetToken 仅是函数体的本地名称。因此,要按照您想要的方式使用它,您需要引用 this.GetToken() 从原型(prototype)中获取函数:

function Graph() {
  //Constructor
  this.Client = null;
}
Graph.prototype.Init = async function Init() {
      tokenResult = await this.GetToken(); 
      console.log(tokenResult)
};
Graph.prototype.GetToken = function GetToken() {
     return Promise.resolve("GetToken Called")
};

g = new Graph()
g.Init()

关于javascript - 声明原型(prototype)并在 NodeJS 中的同一文件中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356955/

相关文章:

javascript - 如何使用 useState() 更新 react-chartjs-2 图

node.js - Node-gyp 找不到 msbuild.exe

javascript - 我可以在 Node.js 和 Express 中运行单个 .js 文件吗?

javascript - 通过 id 获取 fullcalendar fc-event div

javascript - 使用 jQuery/Javascript/GM 在圆的边缘创建标记

javascript - FullCalendar v4 更改所选日期的颜色

node.js - 拦截 knex.js 查询预执行

javascript - 顺风 CSS : Referencing to custom color in tailwind. config.js

javascript - ES 模块何时可以导入名为 export 的 CommonJS?

javascript - TypeError : loginScreen.visibleOfWelcome不是一个函数