使用Fabric.js 1.1.6,我有以下内容:
var rect = new fabric.Rect({});
rect.on('moving', function(obj) {
// I want to retrieve and set properties from the
// object rect from inside this event function
});
是否可以从事件调用的函数内部检索和修改
rect
属性?如果是,该怎么办?
如果不是,那么关于如何从事件函数内部修改rect属性的任何建议?
先感谢您!
-
更新:上面的问题已由@plalx正确回答,但实际上我在更大的范围内有此问题:
function SomeClass()
{
this.rect = new fabric.Rect({});
this.rect.on('moving', function(obj) {
// here, this.rect is undefined
});
}
好吧,在后一种情况下,我不能只在函数内部使用this.rect,因为
this
是指函数,而不是SomeClass。现在,以上三个问题的答案如何?
最佳答案
“是否可以从内部检索和修改rect属性
事件调用的功能?”
不仅可能,而且非常简单;)您应该阅读JavaScript中的closures。
对于问题1
var rect = new fabric.Rect({});
rect.on('moving', function(obj) {
rect.someProperty = 'test';
});
对于问题2
function SomeClass() {
var rect = this.rect = new fabric.Rect({});
this.rect.on('moving', function(obj) {
// here, this.rect is undefined
rect.someProperty;
});
}