JS - 为变量赋值函数 [英] JS - assigning function to variable

查看:230
本文介绍了JS - 为变量赋值函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,以下不会运行a()函数,因此警告框不会出现

As we all know, this following will not run the a() function so the alert box will not appear

// 1st
function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};

我们知道以下代码将运行a()函数警告框'A!'将出现

// 2nd
function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};
a(); // calling function

但是,如果我们运行以下代码, a()函数将被调用警告框'A!'也会出现,就像上面的第二个代码一样

However, if we run following code, the a() function will be called and alert box 'A!' will also appear, just like the second code above

// 3rd
function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};
var x = a(); // assigning function to new variable

问题:
为什么会发生这种情况(第3段)?我们还没有调用a()函数(我目前的理解)。我们不是只是将x赋给a()函数吗?。

QUESTION: why does this happen (on 3rd snippet)? we didn't call the a() function yet (my current understanding). Didn't we just assigning x to a() function?.

推荐答案


我们不是吗?只是将x赋给a()函数?。

Didn't we just assigning x to a() function?.

不,你将一个()的返回值赋给了x。

No, you assigned the returned value from a() to x.

如果您不想拨打 a ,那么

var x = a;

以后再做

x();

这篇关于JS - 为变量赋值函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆