Using the callback function with prototype functions

I am having trouble figuring out a way to pass an object method, rather than sorting the "generic prototype" method on a callback.

function Client() { this.name = "hello"; } Client.prototype.apiCall = function(method, params, callback) { callback(); } Client.prototype.onLogin = function(error, data) { console.log(this.name);// undefined!!!! } Client.prototype.start = function() { var self = this; self.apiCall('rtm.start', { }, self.onLogin) // passing of method like this does not work. } 

I pass the onLogin method, but it does not work. This is the code I rewrote. I previously nested all the methods inside the Client function, but I realized that this is not a way to do this, so now I am trying to use a prototype.

I know that there is some solution linking the onLogin function inside the Client () function, but I want to understand the problem.

+7
javascript
source share
2 answers

You need to associate the apiCall context with the callback using bind :

 Client.prototype.apiCall = function(method, params, callback) { var bound = callback.bind(this); bound(); } 

Otherwise, a global object is set inside onLogin for this.

See Call, Apply And Bind for details.

Basically .bind(obj) returns a function that when called will internally use (obj) like this .
So you create this binding and then call it.

+4
source share

You can use call or apply to bind this , see snippet. I changed the code for the demo. Hope he clarifies things for you.

 function Client() { this.name = "hello"; } Client.prototype = { apiCall: function(method, params, callback) { try { var trial = method.call(this, params); callback.apply(this, [null, trial]); } catch (e) { callback.apply(this, [e, null]); } }, onLogin: function(error, data) { if (error) { Helpers.report('<b style="color: red">' + 'An error occured!</b> <i>' + error.message + '</i>') } else { Helpers.report(this.name, ' (data.result = ' + data.result + ')'); } }, start: function() { Helpers.useCSS(1); // error from this.rtm.start Helpers.report('Command: <code>', 'this.apiCall(this.rtm.start, {will: \'not work\'}, this.onLogin);','</code>'); this.apiCall(this.rtm.start, {will: 'not work'}, this.onLogin); // this.rtm.works is ok Helpers.report('<br>Command: <code>', 'this.apiCall(this.rtm.works, {will: \'work\'}, this.onLogin);', '</code>'); this.apiCall(this.rtm.works, { will: 'work' }, this.onLogin); }, // -------------------------------- // added rtm for snippet demo rtm: { start: function(params) { return anerror; }, works: function(params) { return { result: 'worked, <code>params: ' + JSON.stringify(params) + '</code>' }; } }, }; new Client().start(); //<= here 
 <script src="https://rawgit.com/KooiInc/Helpers/master/Helpers.js"></script> 
+3
source share

All Articles