作为 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: number
在 handleSwipe
函数内声明对象是可行的,不幸的是我必须在其外部声明该对象,以便能够更改分配的值重视并重用它。
问题:如何从 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/