简体   繁体   English

声明原型并在NodeJS的同一文件中使用它

[英]Declare prototype and use it in same file in NodeJS

I have created a function that have prototypes which I will use in other files. 我创建了一个函数,该函数具有将在其他文件中使用的原型。

function.js function.js

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

function GetToken() {
 ...
};

I would use GetToken method outside of the file. 我将在文件外部使用GetToken方法。 so I added GetToken function as prototype 所以我添加了GetToken函数作为原型

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() {
     ...
};

When I run my program I get this error: 当我运行程序时,出现此错误:

GetToken is not defined

Also I would know how to only export the value of the token and not the function ( so that I could use the same token ) 我也知道如何仅导出令牌的值而不导出函数(以便我可以使用相同的令牌)

With function expressions like Graph.prototype.GetToken = function GetToken() the name GetToken is only local to the body of the function. 使用Graph.prototype.GetToken = function GetToken()之类的函数表达式,名称GetToken仅在函数主体中是局部的。 So to use it the way you want to, you need to reference this.GetToken() to get the function from the prototype : 因此,要以所需的方式使用它,您需要引用this.GetToken()以从原型获取函数:

 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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM