【问题标题】:Keeping class this when calling button click function调用按钮单击功能时保持类
【发布时间】:2017-05-29 12:15:49
【问题描述】:

从按钮输入点击功能时,有没有办法保留类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

【问题讨论】:

    标签: javascript jquery ecmascript-6


    【解决方案1】:

    你需要绑定foo

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

    或使用箭头函数

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

    【讨论】:

    • 做到了。这两种方法有区别吗?第二个只是调用函数?那为什么() => this.foo 不工作呢?
    • bind 创建具有限界上下文的新函数,这是 ES5 在回调中保持上下文的方式。 () => blah 创建新的箭头函数并在 ES201Somthing 中引入。它们在某些方面有所不同,但在这种情况下应该“相同”developer.mozilla.org/en/docs/Web/JavaScript/Reference/…“那为什么() => this.foo 不工作?” () => body 创建新的箭头函数 this.foo 只需访问 foo 无需调用。所以你需要this.foo()
    【解决方案2】:

    为什么不为函数 foo 定义参数:

    $("#someButton").click(function(){
      foo(obj);
    });
    
    
    foo(obj){
      // work with obj ... 
    }

    【讨论】:

    • 他如何访问foo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多