【问题标题】:ES6 jQuery bind listener as anonymous function [duplicate]ES6 jQuery绑定监听器作为匿名函数[重复]
【发布时间】:2020-12-05 14:00:01
【问题描述】:

我想将匿名函数绑定到 ES6 类中的 jQuery 事件监听器。

类似:

class MyClass{    
    constructor(){
        $( document ).mousedown( callAnonymous );
    }    
    callAnonymous(e){
        //Need class references here
    }
}

这有简单的语法吗?在网上找不到任何东西。

【问题讨论】:

  • 你在说什么匿名函数?您的代码中没有。

标签: javascript jquery ecmascript-6


【解决方案1】:

你可以像绑定任何普通函数一样绑定它:

$(document).mousedown(this.callAnonymous.bind(this));

【讨论】:

  • 所以使用 .bind(this) 我的 handlerfunc 中仍然有类引用?
  • 是的,这就是绑定的作用。如果将其绑定到this,那么callAnonymous 中的this 将引用类实例。
  • 感谢您的快速回答:)
  • 它必须是this.callAnonymous.bind(this)callAnonymous 是类实例的属性。
猜你喜欢
  • 2011-03-25
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2013-02-08
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多