打字稿"Cannot find name <fieldname>"



我对TypeScript还很陌生。

我创建了一个带有一些私有字段的类。当我试图在类方法中为匿名回调函数中的一个字段赋值时,我会得到错误。。。

(TS) Cannot Find the name '_tokens'

我怀疑存在范围界定问题,但从我对JavaScript的理解来看,这应该不是问题。我不知道该怎么修。有什么主意吗?

请参见。。错误的">populateTokens(("方法。

class SingleSignOn {
private _appTokensURL: string  = "/api/IFSessionCache/Auth/";
private _tokens: string[];
/**
* Initialize an instance of the SingleSignOn class to manage the permissions for the 
* application associated with the application.
*/
constructor() {
this.populateTokens();
};

/**
* Gets a list of permissions tokens associated with the currently logged on user for 
* the application.
*/
private getApplicationTokens(): Q.IPromise<{}> {
return Unique.AJAX.Get(this._appTokensURL, null, ENUMS.AjaxContentTypes.JSON);
};

private populateTokens () {
this.getApplicationTokens().then(
function (data) {
_tokens = <string[]>data; // (TS) Cannot find name "_tokens"
});
};
};

您使用了错误的语法:

this.getApplicationTokens().then(
(data) => {
this._tokens = <string[]>data; // note: turned into an arrow function and added the `this` keyword
});

注意如果继续使用function() ...语法,则this关键字将不指向类实例,而是指向callee

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

问候

类的属性没有作用域,只要它们所属的对象存在,它们就存在,所有可以访问该对象的东西也可以访问其所有属性。但是,属性总是必须在其对象上访问,例如方法内部的something._tokensthis._tokens。此外,你必须确保this是你认为的,在你的情况下,你必须使用箭头函数在回调中访问正确的this

this.getApplicationTokens().then( (data) => {
this._tokens = data as string[];
});

我认为您只是错过了_tokens:中的this关键字

this._tokens = <string[]>data;

相关内容

最新更新