[英]Access Outside Variable inside a internal function typescript
我在函數外部有一個變量,需要更改該值。 我通常使用“ this”來訪問變量,但是在代碼的那一點上,“ this”是不可訪問的。
export class GamesDetailPage {
details : any = {};
type : String;
level : Number;
cards : any = {}; // THE VARIABLE I WANT TO SET THE VALUE
constructor(public navCtrl: NavController, public http: HttpClient , private device: Device, private serviceProvider: ServicesProvider,
public navParams: NavParams
) {
this.type = navParams.get('gameType');
this.level = navParams.get('gameLevel');
}
ionViewDidLoad() {
this.getCards(); // WHERE I CALL THE METHOD
}
getCards(){
var deviceUUID = this.device.uuid;
var platform = this.device.platform;
var cardsReq = {"gameType": this.type ,"gameLevel": this.level};
var dialog = this.dialogs;
this.serviceProvider.getCards(deviceUUID, platform, cardsReq)
.then(function (res){
this.cards = res;// HERE I WANT TO SET THE VARIABLE BUT "THIS" IS UNDEFINED
})
.catch(function(err){
console.log("Error");
})
}
}
在這里,您需要像以前的(function(){
方法中那樣使用ES6 arrow function
, this
並不引用該類,但是在es6中,它將使用...
箭頭函數表達式的語法比函數表達式短,並且沒有自己的語法
.then(
(res) => {
this.cards = res; // Should work now
}
)
因為外面this
被函數的this
遮蓋了。 最直接的方法也是推薦的方法是在打字稿中使用箭頭功能。
將lambda函數更改為:
(res) => {}
另一個老的解決方案是保存this
一個臨時變量:
that = this
然后在您的lambda函數中訪問它。
在JavaScript中, this
與當前函數有關。 TypeScript在編譯代碼時只是隱藏了這一事實。
因此,您可以做兩件事。
首先,您可以使用ES6箭頭功能(TypeScript將為您完成this
作用域)
.then((res) => {
this.cards = res;
})
或者,您可以自己處理
getCards(){
var _this = this;
// More code
.then(function (res){
_this.cards = res;
})
如果您檢查兩種情況的轉譯輸出,它們應該幾乎相同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.