javascript函数指针和 "this"

标签 javascript jquery jsplumb

使用 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/

相关文章:

javascript - 如何让 PlotBands 数据显示在 HighChart 图表上?

javascript - 使用移动数据会导致意外结果

javascript - 突出显示单词的超时功能无法正常工作

javascript - JsPlumb 从起始元素获取所有连接

javascript - this.class 与 this.getAttribute ('class' )

jquery - CSS 当前类未被删除

jquery - 聊天小部件的桌面通知

javascript - Jsplumb 分离连接

javascript - jsPlumb 点击单个项目

javascript - 如何使用 javascript 为动态 html 表引入分页和排序?