Nativescript Angular:无法从函数内部读取对象(this.undefined?)

Nativescript Angular: Can't read object from inside a function (this. undefined?)

作为 Nativescript 和 Typescript 的初学者,我经常只是尝试使用我在示例中找到的代码。 现在我有一个组件可以生成 Gridlayout 并对手势(例如滑动或平移)做出反应。简化的代码如下所示:

import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import { SwipeGestureEventData, GesturesObserver, GestureTypes, PanGestureEventData } from "ui/gestures";

export class CardComponent implements OnInit {
    constructor( ) { }
    prevDeltaX: number = 0;

    ngOnInit() {
        //initialising of the layout is unimportant 

        //Calls the funtion that creates the Layout and handles gestures
        for (var key in this.SourceArray) {
            this.handleSwipe(key);
        }
    }

 handleSwipe(key: any) {
    // grid is this GridLayout Object created, cut out here

    grid.on(GestureTypes.pan, function (args: PanGestureEventData) {
        console.log(this.prevDeltaX);  //Error here
    });
}

每当我在屏幕上滑动时,函数都会产生错误,而不是显示 0: TypeError: Cannot read property 'prevDeltaX' of undefined

let prevDeltaX: numberhandleSwipe 函数内声明对象是可行的,不幸的是我必须在它之外声明对象,以便能够更改分配的值并重用它。

问题:如何从 Typescript 的函数中访问(和更改)对象?

使用arrow functions捕捉正确的this:

grid.on(GestureTypes.pan, (args: PanGestureEventData) => {
    console.log(this.prevDeltaX); 
});

箭头函数工作的原因是因为 this 不会在箭头函数内部改变(即这将是 CardComponent 实例),而 this 会根据调用而改变上下文,如果你使用 function() {}.