我创建了一个具有原型(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/