开发者

return vs. callback in a Javascript function

开发者 https://www.devze.com 2023-03-09 05:04 出处:网络
Say I write this function... var say开发者_如何学JAVAHi = function() { return \"hi\"; } alert(sayHi()); will return \"hi\".

Say I write this function...

var say开发者_如何学JAVAHi = function() {
  return "hi";
}

alert(sayHi()); will return "hi".

Now if I write it this way...

var sayHi = function(callback) {
  callback("hi");
}

How do I display "hi" with this function?

Based on an example here: http://nowjs.com/doc


You pass a function to sayHi, so I imagine this:

sayHi(alert);


you must have defined some callback function or pass a anonymous function:

var sayHi = function(callback) {
  callback("hi");
}

sayHi(function(message){
  alert(message);
});


Try this:

sayHi(function(msg){
    alert(msg)
});

Your new sayHi function doesn't return a value, so you have to perform the alert in the callback function.


sayHi(function(value) {
    alert(value);
});


sayHi(function(msg) {
    alert(msg);
});

You have to invert your thinking process when using callbacks. Instead of writing the next operation first, you write the next operation last.


Here in example callback is a function. So you should pass function argument.

You may do this in 2 ways:

var some_fun = function(some_str) {
    alert(some_str);
}

var sayHi = function(callback) {
  callback("hi");
}

    sayHi(some_fun)

or you can pass function when you call it:

var sayHi = function(callback) {
  callback("hi");
}

sayHi(function(some_str){
  alert(some_str);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消