Callback this context

Dans l'application:

var bootstrap = new Bootstrap(); bootstrap.init( this, this.onBootstrapComplete ); 

Dans Bootstrap:

 this.init = function( app, completeHandler ){ _app = app; _completeHandler = completeHandler; ... } ... var _allReady = function(){ _completeHandler( _app ); } 

Dans l'application:

 this.onBootstrapComplete = function( app ) { app.something(); app.someValue = ... } 

Je voulais avoir ce contexte à l'intérieur deBootstrapComplete. Cela fonctionne mais ça ne semble pas juste 🙂

Si nous disions que je voulais appelerBootstrapComplete directement à partir de l'application, je devrais l'appeler .onBootstrapComplete ( ceci ).

Comment puis-je le faire afin que mon onBootstrapComplete ressemble à ceci:

 this.onBootstrapComplete = function() { this.something(); this.someValue = ... } 

Je recommande d'utiliser underscore.js. Voir http://underscorejs.org/#bind pour plus d'informations.

 this.onBootstrapComplete = _.bind( function() { ... this.someFunction(); // this context is available now ... }, this ); 

this est évalué lorsque la fonction est appelée. Dites que vous utilisez this dans une fonction f .

Il existe essentiellement deux façons d'appeler f :

(expr).f() si f est appelé comme propriété sur un objet, this évaluera l'objet expr .
f() Dans ce cas, this évaluera la window .

Puisque vous passez la fonction sur bootstrap , il ne peut appeler la fonction que f() .

Vous pouvez utiliser une fermeture:

 var self = this; this.onBootstrapComplete = function() { self.something(); self.someValue = ... } 

Alternativement, vous pouvez utiliser une fonction pour f.apply() la fonction de manière appropriée:

 function bind(context, f){ return function() { return f.apply(context, arguments); } } this.onBootstrapComplete = bind(this, function() { this.something(); this.someValue = ... }); 

Ou avec ECMAScript 5, il existe déjà une fonction de liaison [MDN] :

 this.onBootstrapComplete = function() { this.something(); this.someValue = ... }.bind(this);