简体   繁体   中英

Javascript callback vs inline initialing 'callback'

I am new to javascript, I have gone through tutorials about callbacks, but I don't see any that answers this, both method below offers the same results, the only difference I see is callback allows dynamically passing in a callback function.

Are there other advantages, I am missing?

Thank you.

Callback

function logOne(callback) {
  setTimeout(() => {
    console.log("one");
    callback();
  }, 1000);
}

function logTwo() {
  console.log("two");
}
logOne(logTwo); // one, two

No Callback

function logOne() {
  setTimeout(() => {
    console.log("one");
    logTwo();
  }, 1000);
}

function logTwo() {
  console.log("two");
}
logOne(); // one, two

Your first example is more flexible: You can use any callback, not just logTwo .

Both have their uses, it depends on whether you need the flexibility or whether logOne should be specifically tied to logTwo .

Callback of function : If you want to do some operation on some event Like show time on click of a button. Then you override onclick function for that button. So whenever (independent on time) that button is clicked, that application internal framework will call onclick event and your onclick function will be called.

Normal function : Every function is normal function

Calling a function is when you actually do the function.

Passing a function is when function A needs function B in order to work. So when you call function A, you pass it function B as an argument. In this case you are not calling function B, instead you are providing it to function A so that function A can call it.

Your second example create a tight coupling between logOne and logTwo functions. This way you end up with a logOne function that can't be reused since it only works with one exact function.

By passing a callback, you make your function more flexible and generalized. Now it is able to work with a wide range of other functions as long as they have the same "shape" - same number of arguments in a same order.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM