简体   繁体   中英

Keeping class this when calling button click function

Is there a way to keep the class this when entering a click function from a button?

For example:

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 
  }

But I want to access this.obj in foo() .

You need to bind foo

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

or use arrow function

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

Why are you not defining a parameter for the function foo:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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