javascript - Nativescript Angular : Can't read object from inside a function (this. 未定义?)

标签 javascript angular typescript nativescript angular2-nativescript

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

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: 类型错误:无法读取未定义的属性“prevDeltaX”

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

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

最佳答案

使用arrow functions捕获正确的this:

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

箭头函数起作用的原因是因为 this 不会在箭头函数内部改变(即,这将是 CardComponent 实例),其中 this > 如果您使用 function() {},则会根据调用上下文而变化。

关于javascript - Nativescript Angular : Can't read object from inside a function (this. 未定义?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906393/

相关文章:

javascript - 当表单无效时如何禁用按钮?

javascript - Angular 2 ng 用于相反顺序和相同索引

javascript - 通过 JSON/AJAX 更新 HTML

javascript - 使用循环增加CSS属性值

angular - Http 请求的加载指示器

angular - (404未找到)加载http ://localhost:4200/angular2-datatable/datatable

TypeScript:从接口(interface)方法返回类的实例

javascript - 动态路由列表项

typescript - 如何使用 Typescript 定义 knex 迁移

javascript - 用普通的 Javascript 将具有相同类的元素彼此相邻包装