gpt4 book ai didi

javascript - 从原型(prototype)中的事件访问 "this"

转载 作者:行者123 更新时间:2023-11-30 10:08:37 24 4
gpt4 key购买 nike

考虑以下代码...使用 Hammer.js 但我认为它可能是一个通用的 Javascript 问题:

var drawLayer = new DrawLayer(document.getElementById('canvasContainer'));

function DrawLayer(targetElement) {
this.foo = "bar";

this.gestureDetection = new Hammer.Manager(targetElement);
this.gestureDetection.add(new Hammer.Pan({
direction : Hammer.DIRECTION_ALL,
threshold : 0
}));
this.gestureDetection.add(new Hammer.Press({
time : 0,
threshold : 5
}));
this.gestureDetection.on("press", this.drawBegin);
this.gestureDetection.on("panmove", this.drawMove);
this.gestureDetection.on("panend pressup", this.drawEnd);

this.drawBegin("INIT TEST");
}

DrawLayer.prototype.drawBegin = function (gestureData) {
console.log(typeof(this.foo));
console.log("DRAW BEGIN!");
}

DrawLayer.prototype.drawMove = function (gestureData) {
console.log(this.foo);
console.log("DRAW MOVE!");
}

DrawLayer.prototype.drawEnd = function (gestureData) {
console.log(this.foo);
console.log("DRAW END!");
}

当我第一次运行它时,我得到了预期的结果:

string
DRAW BEGIN!

但是当实际处理手势时(即当通过事件调用绘图时),我得到:

undefined
DRAW BEGIN!

更多关于这一点 - 似乎在处理任何这些 drawBegin/etc 时。方法,“this”是未定义的,好像它以某种方式失去了范围?

我想要一个解决方案和一个解释。谢谢!

最佳答案

您可以像这样将“this”绑定(bind)到事件回调:

this.gestureDetection.on("press", this.drawBegin.bind(this));

当回调被事件触发时,它应该有正确的“this”。

关于javascript - 从原型(prototype)中的事件访问 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27731756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com