0

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)
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Linghua Jin
  • 570
  • 2
  • 6
  • 22

1 Answers1

3

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)); 
jfriend00
  • 683,504
  • 96
  • 985
  • 979