据说回调通过将回调函数的值(其函数定义)传递给“高阶”函数的参数,在该参数中传入并执行,从而为高阶函数添加功能。
似乎我们可以通过从另一个执行函数内部调用外部函数来完成同样的事情。
以下内容更好地说明了我想说的内容。
// ************************ 使用回调 ************************ ****************************
function A() { // this is the callback function
return 'hello';
};
function B(callback) { // this is considered a 'higher-order' function because it takes a
// function definition as a parameter. the function definition of A
// -- taken from A in Global memory -- is assigned to callback
var output = callback(); // we call callback and run it
// the value of callback, is assigned to the variable output
console.log(output);
console.log("goodbye")
};
B(A); // logs 'hello' 'goodbye'
// ******* 将上述与从另一个函数内部调用外部函数进行比较 *****
function A() {
return 'hello';
};
function B() {
var output = A(); // we call function A, from inside function B,
// the value returned by A, is assigned to a variable inside B
console.log(output);
console.log("goodbye")
};
B(); // logs 'hello' 'goodbye'
虽然两者在返回值方面没有区别,但它们的执行方式却有所不同。
回调函数接受 A 的函数定义并将其附加到一个名为回调的新名称。回调被执行,并在回调的本地执行上下文中运行。
将此与从 B 内部调用 A 时发生的情况进行比较,A 在其自己的本地执行上下文中执行。
也许这个例子太简单了,看不出这两个之间的差异会帮助我理解什么时候使用一个而不是另一个。
小唯快跑啊
相关分类