对返回函数的函数感到困惑

Confusion on function that return a function

本文关键字:函数 返回      更新时间:2023-09-26

帮助我理解以下这段代码。我仍然是JavaScript的新手。

我们知道以下代码将运行带有 A 消息的警报框

// 1
function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
var x = box();

我们知道以下内容将运行警报框 A,然后是警报框 B

// 2
function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
var x = box();
x();

但是在下面的代码中,行为就像代码段 1 一样。我希望只运行警报框 B。

// 3
function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
var x = box; // no invoking box function
x();

问题:为什么片段 3 会发生这种情况?我们不是只调用x函数吗?从代码段 1 和 2 中我们知道运行 x() 会触发警报框 B,但为什么它没有出现在代码段 3 上?

当你编写var x = box;时,你将函数"BOX"存储在变量X上。你没有执行你的盒子函数。要执行,您需要使用括号作为box()

由于您刚刚存储了函数并且没有运行它,因此当您调用x()时,将产生与调用 box() 相同的结果。

简单示例

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

当你打电话给print('xcode')时会发生什么?- 您的浏览器将提醒"XCODE",因为您刚刚使用该参数调用了函数。

现在: var x = print;

在这里,我将"打印"函数复制到"x"变量。

最后,当你打电话给x('xcode again')时会发生什么?- 您的浏览器将再次提醒"XCODE",就像以前一样。

看起来你已经理解了95%,但你最后出轨了。

您是对的,在第三个代码段中,我们将函数保存到变量x

function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
var x = box; // no invoking box function
x();

但是因为我们实际上并没有调用box(),所以我们只是将函数存储在新变量中,var x 。所以通过调用x(),我们本质上只是在调用box()

我们唯一会得到alert('B')的时间是将box函数的返回值保存到一个新变量,然后调用该新变量,就像我们在片段 2 中所做的那样。

我希望这有所帮助。

function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
//fires box() thus firing alert('A');
//returns a function that holds alert('B');
var x = box();

.

function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
//fires box() thus firing alert('A');
//returns a function that holds alert('B');
var x = box();
//fires the returned function alert('B');
x();

.

function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
//sets x EQUAL to box, nothing special nothing happens
var x = box; // no invoking box function
//fires box() thus firing alert('A');
//returns a function that holds alert('B');
x();

它会提醒A,因为您正在调用box

x是对函数box的引用。当你写x()它与调用box()相同。它不会提醒B,因为您没有调用通过调用 box 返回的函数。

function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
var x = box; // no invoking box function
x()();

这与执行此操作相同:

function box() {
  alert('A');
  return function() {
    alert('B');
  }
}
// x1 is a reference to the function box, which alerts, and returns a function
var x1 = box;
// x2 is now the return value of box, the function. A side effect is that
// "A" is alerted.
var x2 = x1();
// Now you're calling the function returned by `box`, which alerts "B".
x2(); // Alerts B