javascript - Prevent loss of context for 'this' variable in a function passed as a parameter -
question
how can prevent loss of context this
variable inside function passed parameter?
simple example, in jsfiddle
var = { start: function() { b.start( this.process ); }, process: function( justaparameter ) { justaparameter += ' of multiple contexts!' this.finish( justaparameter ); }, finish: function( finishparameter ) { console.log( finishparameter ); } } var b = { start: function( justafunction ) { justafunction( 'hello world' ) } } a.start();
expected output
hello world of multiple contexts!
received output
typeerror: this.finish not function
you can use bind
bind value of this
process()
method when it's referenced argument
start: function() { b.start( this.process.bind(this) ); },
Comments
Post a Comment