繁体   English   中英

调用按钮单击功能时保持此类

[英]Keeping class this when calling button click function

通过按钮输入单击功能时,是否可以将this保留为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

您需要绑定foo

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

或使用箭头功能

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM