I'm trying to wrap my head around javascript callback functions. I tried the following piece of code:
var callbackTester = function(callback) {
var tryMe = "Are you ready, ";
callback(tryMe);
}
var createMessageHandler = function(client) {
this.client = client;
this.result = function(foo){
console.log(foo + " "+ this.client);
}
};
(new createMessageHandler("John")).result(callbackTester);
Instead of "Are you ready, Jason", I get the entire callback function displayed followed by name:
function (callback) {
var tryMe = "Are you ready, ";
callback(tryMe);
} John
Can someone help me understand how to fix this?
Your foo
argument is not a string, it's a callback which you need to call. One of the possible solutions is:
var callbackTester = function (callback) {
var tryMe = "Are you ready, ";
callback(tryMe);
};
var createMessageHandler = function (client) {
this.client = client;
this.result = function (foo) {
foo(function (msg) {
console.log(msg + " " + this.client);
}.bind(this));
}
};
(new createMessageHandler("John")).result(callbackTester);
Mind .bind(this)
- you need to do that in order to preserve this.client
from the outer scope.
More on the bind
function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Note: I don't quite understand the purpose of your code though. Aren't you getting into a callback hell? Try monads/promises instead.
new createMessageHandler
isn't intuitive. IMHO it should either be new MessageHandler()
or just createMessageHandler()
You defined a callbackTester
function, and it takes a callback as argument, so you have to give it a callback, otherwise it will never work. Also, you have to return
that callback. Otherwise you'll never get anything but the function itself. Here is a solution:
var callbackTester = function(callback) {
var tryMe = "Are you ready,";
return callback(tryMe);
}
var createMessageHandler = function(client) {
this.client = client;
this.result = function(foo){
console.log(foo + " "+ this.client);
}
}
(new createMessageHandler("John")).result(callbackTester(function(phrase) { return phrase; }));
// Are you ready, John
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.