Javascript 函数如“var foo = function bar() ..."? [英] Javascript functions like "var foo = function bar() ..."?

查看:32
本文介绍了Javascript 函数如“var foo = function bar() ..."?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码是这样的(语法可能看起来很奇怪,但据我所知,它没有任何问题.或者有没有?)

The code goes like this (The syntax may seem odd but as far as I know, there is nothing wrong with it. Or is there?)

var add=function addNums(a, b) {                     
   return a+b;
 }                     
 alert("add: "+ add(2,3));           // produces 5
 alert("addNums: "+addNums(2,3));        // should also produce 5

addNums() 被声明为一个函数.所以,当我向它传递参数时,它也应该返回结果.

addNums() is declared as a function. So, when I pass the parameters to it, it should also return the result.

那么,为什么我没有收到第二个警告框?

Then, why am I not getting the second alert box?

推荐答案

您正在看到一个 命名函数表达式 (NFE).

匿名函数表达式是您将没有名称的函数分配给变量的地方1:

An anonymous function expression is where you assign a function without a name to a variable1:

var add = function () {
  console.log("I have no own name.");
}

命名函数表达式是您将命名函数分配给变量的地方(惊喜!):

A named function expression is where you assign a named function to a variable (surprise!):

var add = function addNums() {
  console.log("My name is addNums, but only I will know.");
}

函数的名称仅在函数本身中可用.这使您无需知道函数的外部名称"即可使用递归 - 即使不必首先设置一个(想想回调函数).

The function's name is only available within the function itself. This enables you to use recursion without necessarily knowing the "outside name" of the function - even without having to set one in the first place (think callback functions).

您选择的名称​​隐藏一个现有名称,因此如果在别处定义了另一个addNums,它不会被覆盖.这意味着您可以使用任何您喜欢的名称,而不必担心范围界定问题或破坏任何内容.

The name you choose shadows an existing name, so if another addNums is defined elsewhere it will not be overridden. This means you can use any name you like without fear for scoping problems or breaking anything.

过去你会使用 arguments.callee 在不知道其名称的情况下引用自身内部的函数.但是 JavaScript2 正在取消对此的支持,因此现在 NFE 是实现此目的的正确方法.

In the past you would have used arguments.callee to refer to a function inside itself without knowing its name. But support for that is being removed from JavaScript2, so NFEs are the correct way to do this nowadays.

这里有很多关于这个主题的内容:http://kangax.github.io/nfe/

Here is a lot of stuff to read on the topic: http://kangax.github.io/nfe/

1 没有必要将它赋值给一个变量,它只是作为一个例子来区分它与普通的函数声明.它可以是 JS 需要表达式(例如,函数参数)的任何其他上下文.

1 Assigning it to a variable is not necessary, it just serves as an example to distinguish it from a plain function declaration. It could be any other context where JS expects an expression (a function argument, for example).

2 如果您有 严格模式 有效并尝试使用 arguments.callee.

2 You will receive an error if you have strict mode in effect and try to use arguments.callee.

这篇关于Javascript 函数如“var foo = function bar() ..."?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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