javascript - 调用按钮单击功能时保持类 this

标签 javascript jquery ecmascript-6

当从按钮输入点击函数时,有没有办法保留类this

例如:

class MyClass extends FooClass{

  constructor (obj) {

    super (obj)

    this.obj= obj;

    $("#someButton").click(this.foo);
  }

  foo(){
    this.obj; // undefined because this is now #someButton and not MyClass 
  }

但我想在 foo() 中访问 this.obj

最佳答案

您需要绑定(bind)foo

$("#someButton").click(this.foo.bind(this));

或使用箭头功能

$("#someButton").click(() => this.foo());

关于javascript - 调用按钮单击功能时保持类 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44242279/

相关文章:

javascript - 如何使用 JavaScript 或 jQuery 将动态 URL 从绝对 trim 为相对

jquery - 将父代的 ID 添加到 append 克隆的 ID,同时将重命名的克隆 append 到多个父代

javascript - 商店更改后 React redux UI 未更新

javascript - ES6 运行时交换模块

javascript - 一页上嵌入多个字体

javascript - Raphael js - 在保留单个元素不透明度的同时为组设置动画不透明度

javascript - 如何在图表(chartJS)中添加长度条的背景颜色?

javascript - 如何改变div的颜色

jquery - 你能通过 url 发送 JSON 吗?

javascript - ES6 的下划线方法