JavaScript callback()

参考:MDN

解释

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

callback() function 是作为argument传到另一个函数的函数。

实例

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

等价于

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput() {
  var name = prompt('Please enter your name.');
  greeting(name);
}

processUserInput();

分析

processUserInput(greeting); 传进去greeting(greeting 在函数内部就用callback表示了),先执行输入name,然后执行greeting。如果我想再实现processUserInputfareWell()函数,我只需要传processUserInput(fareWell);
第二种方法的话先然就不能改了,如果我想再加一个fareWell()函数,就只能重新写一个新的函数processUserInput2()

猜你喜欢

转载自blog.csdn.net/wangzihahaha/article/details/86656242