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) ); }, 

fiddle


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -