从原型中的事件访问“this”
Accessing "this" from event in prototype
请考虑以下代码...使用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"绑定到事件回调,如下所示:
this.gestureDetection.on("press", this.drawBegin.bind(this));
当回调由事件触发时,它应该具有正确的"this"。
"this" 的值取决于调用函数的方式。
在第一种情况下,您直接从 DrawLayer 类调用 drawBegin 函数:
this.drawBegin("INIT TEST");
在这种情况下,此变量表示绘图层对象。
通过事件调用函数时
this.gestureDetection.on("press", this.drawBegin);
"this"变量可以被函数"on"包装以表示其他任何内容(通常是事件本身或触发事件的对象)。
尝试将代码更改为以下内容,看看它是否有效:
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.drawBeginWrapper);
this.gestureDetection.on("panmove", this.drawMove);
this.gestureDetection.on("panend pressup", this.drawEnd);
var _self = this;
this.drawBeginWrapper = function(gestureData) {
_self.drawBegin(gestureData);
}
this.drawBegin("INIT TEST");
}
相关文章:
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- 为什么我不能在 ajax 成功中访问 $(this)
- 在接受功能上访问燃料UX标语牌中的“this”
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- 在jQuery中,我如何从$.ajax回调函数访问$(this)
- TypeScript:在对象文字字段中的访问器中访问外部“this”
- JavaScript 访问函数构造函数中的“this”
- React Native can'无法在render()方法之外访问this.ops
- 通过函数传递“this”时,我是否可以无法访问“this”的属性
- 如何使用“self = this”访问类属性
- 使用“this”访问对象的值
- arguments属性可以由this访问.some_function.arguments?实际上我无法解释
- 使用let初始化的函数在被this访问时不被替换
- 隐藏匿名JavaScript函数中的变量,但使用“this”访问它们
- 如何使用$(this)访问调用Javascript函数的按钮的id
- 在Javascript中无法通过this访问const变量
- 如何在jQuery中使用$(this)访问子元素?
- 无法使用“this”访问对象.“this”指向“窗口”对象
- 使用jQuery的$(this)访问内部文本
- 使用this访问对象内的对象名称