【问题标题】:Nativescript Angular: Can't read object from inside a function (this. undefined?)Nativescript Angular:无法从函数内部读取对象(this.undefined?)
【发布时间】:2017-05-11 04:11:28
【问题描述】:

作为 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 的函数中访问(和更改)对象?

【问题讨论】:

    标签: javascript angular typescript nativescript angular2-nativescript


    【解决方案1】:

    使用arrow functions 捕获正确的this

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

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

    【讨论】:

    • 那行得通。非常感谢您的解决方案和解释!
    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 2018-10-26
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多