无法从委托函数访问 Class 属性
Can't Access Class Property From Delegate Function
这里是长期的 .Net 开发人员,负责将一堆旧的 JS 代码转换为新的 ES6 JS 模块。我正在尝试 运行 下面的(您会想到的)简单代码,但是当调用 jumpToVideoNew 时,委托函数中的 this.allowVidJump 无法访问 class 属性 允许视频跳转。我正在尝试设置一个简单的定时延迟,这样调用代码就不能重复敲击 jumpToVideoNew 函数。我理解变量失去范围的概念,但我尝试设置 _this = this;并在委托中使用 _this 也没有成功。还尝试将对变量的引用传递给函数并以这种方式访问它,但也没有运气。在这么简单的事情上花 2 个小时提醒我为什么我会尽可能避开 javascript。
export class WebUtility {
constructor() {
this.allowVideoJump = true;
this.delay = function () { this.allowVidJump = true; };
}
jumpToVideoNew() {
if (this.allowVideoJump) {
this.allowVideoJump = false;
setTimeout(this.delay, 1000);
}
}
}
使用匿名箭头函数
JS中的function
关键字创建了一个新的范围以及一个新的this
(你刚刚定义的function
=== this
),所以this.allowVidJump
本质上是(function() {}).allowVidJump
在那个范围内
尝试这样的事情:
export class WebUtility {
constructor() {
this.allowVideoJump = true;
this.delay = () => { this.allowVidJump = true; }; // anonymous lambda
}
jumpToVideoNew() {
if (this.allowVideoJump) {
this.allowVideoJump = false;
setTimeout(this.delay, 1000);
}
}
}
这里是长期的 .Net 开发人员,负责将一堆旧的 JS 代码转换为新的 ES6 JS 模块。我正在尝试 运行 下面的(您会想到的)简单代码,但是当调用 jumpToVideoNew 时,委托函数中的 this.allowVidJump 无法访问 class 属性 允许视频跳转。我正在尝试设置一个简单的定时延迟,这样调用代码就不能重复敲击 jumpToVideoNew 函数。我理解变量失去范围的概念,但我尝试设置 _this = this;并在委托中使用 _this 也没有成功。还尝试将对变量的引用传递给函数并以这种方式访问它,但也没有运气。在这么简单的事情上花 2 个小时提醒我为什么我会尽可能避开 javascript。
export class WebUtility {
constructor() {
this.allowVideoJump = true;
this.delay = function () { this.allowVidJump = true; };
}
jumpToVideoNew() {
if (this.allowVideoJump) {
this.allowVideoJump = false;
setTimeout(this.delay, 1000);
}
}
}
使用匿名箭头函数
JS中的function
关键字创建了一个新的范围以及一个新的this
(你刚刚定义的function
=== this
),所以this.allowVidJump
本质上是(function() {}).allowVidJump
在那个范围内
尝试这样的事情:
export class WebUtility {
constructor() {
this.allowVideoJump = true;
this.delay = () => { this.allowVidJump = true; }; // anonymous lambda
}
jumpToVideoNew() {
if (this.allowVideoJump) {
this.allowVideoJump = false;
setTimeout(this.delay, 1000);
}
}
}