关于函数声明的困惑 [英] Confusion about function declaration

查看:94
本文介绍了关于函数声明的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将一个命名函数分配给一个变量,为什么我无法访问指定的函数:

  var a = function b(){
console.log(Hello World);
}
a()// hello world;
b()// b未定义
b // b未定义

在这个时候,我不能删除 a 变量,但是我可以删除 b ,当我删除 b a 的函数仍然可以在那里

  delete a // false 
delete b // true
a()// Hello World

b 函数不仅仅被 a ,而不是复制,那么为什么 a 函数仍然存在?

解决方案

如果使用命名函数表达式(不是函数声明!),函数的名称只能在函数内部访问。



规范(标识符是指函数的名称,即函数标识符(){} ):


可以从 FunctionExpression FunctionBody 中引用ssion ,以允许函数递归调用自身。然而,与 FunctionDeclaration 不同, FunctionExpression 中的标识符不能被引用,也不会影响包含 FunctionExpression 的作用域。

>







但我可以删除 b


不,你不能。当您传递任何不是对 delete 的引用的引用或者引用无法解析时,它会返回 true




这是一篇关于所有函数定义内容的精彩文章: http://kangax.github.io / nfe /

If I assign a named function to a variable, why I can't access to the named function:

var a = function b() {
    console.log("Hello World");
}
a() // hello world;
b() // b is not defined
b  // b is not defined

and at this time, I can not delete the a variable, but I can delete b, when I delete the b, the a's function can still there

delete a //false
delete b //true
a()  //Hello World

the b function isn't just referenced by the a, not copy, so why the a function is still there?

解决方案

If you use a named function expression (not a function declaration!), the name of the function is only accessible form inside the function.

From the specification ("Identifier" refers to the name of function, i.e. function Identifier() {}):

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.


but I can delete b

No, you can't. When you pass anything that is not a reference to delete or the reference cannot be resolved, it will return true.


This is a great article about all the function definition stuff: http://kangax.github.io/nfe/.

这篇关于关于函数声明的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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