How to get callback to work with “this” in class s

2019-01-29 11:58发布

This question already has an answer here:

I have a question about following code to print out "this.text".

I need to have a wrapper function to make it work. This is too troublesome.

Is there a simpler way (without additional wrapper) to get it work?

  function Class1() {
    this.text = "test";
  }

  Class1.prototype.show = function() {
    console.log(this);
    console.log(this.text);
  }

  var testClass = new Class1();

  function funWithCallBack(cb) {
    cb();
  }

  // it will show "undefined" because "this" scope changes to window
  funWithCallBack(testClass.show); 

  function wrapper() {
    testClass.show();
  }

  // this one will work but troublesome
  funWithCallBack(wrapper)

1条回答
混吃等死
2楼-- · 2019-01-29 12:07

You can use an anonymous function like this:

// it will show "undefined" because "this" scope changes to window
funWithCallBack(testClass.show); 

to this:

// anonymous function to use the right object for the method
funWithCallBack(function() {
    testClass.show()
}); 

Your problem occurs because when you pass testClass.show as the callback, it just gets the function reference and there is no association with testClass any more. But, you can create a temporary function that binds them together using .bind(), but it isn't supported in some older browsers which is why I generally just use the anonymous function.

The .bind() implementation would look like this:

// use .bind() to make sure the method is called in the right object context
funWithCallBack(testClass.show.bind(testClass)); 
查看更多
登录 后发表回答