mercredi 22 avril 2015

Prevent loss of context for 'this' variable in a function passed as a parameter

Question

How can I prevent the loss of context for this variable inside a function passed as a parameter?

Simple Example, also in JSFiddle

var a = {
    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 is not a function

Aucun commentaire:

Enregistrer un commentaire