javascript命名函数表达式 – 范围可访问性

参见英文答案 >
var functionName = function() {} vs function functionName() {}                                    37个

>            
Javascript named function as an expression                                    1个

我正在关注
John Resig’s Secrets of JS ninja slides,我发现了一些我不太清楚的事情.以下代码定义了命名函数表达式:

var ninja = function myNinja(){
  console.log(myNinja); // function myNinja() {...}
};
myNinja; // undefined

正如我所看到的,在当前范围内(假设它是全局的),ninja是保存对命名函数myNinja的引用的变量. ninja变量可以在范围内访问 – 这很清楚,但myNinja在范围内是不可访问的(但它可以在自己的函数内访问).怎么会?

如果我定义一个函数(不使用函数表达式,但函数声明):

function Cheese() {
  console.log(Cheese);
}

然后它可以在当前范围内访问.我知道这就是这样 – 但有人可以解释为什么会这样吗?

最佳答案 John Resig在他的着作“
The Secrets of the JavaScript Ninja”中对这个概念作了精彩的解释.

http://jsninja.com/

以下是本书的引用:

4.2.4.内联命名函数

 <script type="text/javascript">
  var ninja = function myNinja(){ 
      assert(ninja == myNinja, "this is named two things at once!"); 
  };
  ninja(); 
  assert(typeof myNinja == "undefined",
    "But myNinja isn't defined outside of the function."); 
 </script>

This listing brings up the most important point regarding inline
functions: even though inline functions can be named, those names are
only visible within the functions themselves.

Remember the scoping rules we talked about back in chapter 3? Inline
function names act somewhat like variable names, and their scope is
limited to the function within which they’re declared.

3.2.1.范围和功能

Variable declarations are in scope from their point of declaration to
the end of the function within which they’re declared
, regardless of
block nesting.

如果您想更多地了解这个概念,本书将对您有所帮助.

点赞