使用 jsPlumb 进行绑定(bind),我将一个方法作为变量传递以用作回调。当它被调用时,“this”不是该方法所属的对象。我如何才能访问该方法的对象实例,以便访问它的变量和其他成员函数?
我无法控制回调调用方法,它是一个单独的库。我所做的就是从我的对象 init 方法中调用绑定(bind)。我希望我的 _connection
方法中的 this
是它的对象。
jsPlumb.bind('connection', this._connection);
最佳答案
任何函数
的this
的值为determined when it's called 。 函数
实际上与“对象”没有其他联系,除了它是否被称为object.method()
或 method.call(object)
.
因此,要传递具有固定this
值的函数
,它需要是bound :
jsPlumb.bind('connection', this._connection.bind(this));
jQuery 还包括一个包装器和兼容性填充 jQuery.proxy()
:
jsPlumb.bind('connection', $.proxy(this._connection, this));
关于javascript函数指针和 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17387068/