This question already has an answer here:
- Callback this context [duplicate] 2 answers
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)
You can use an anonymous function like this:
to this:
Your problem occurs because when you pass
testClass.show
as the callback, it just gets the function reference and there is no association withtestClass
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: