无法执行也被引用的命名函数

时间:2016-01-13 20:13:08

标签: javascript

我正在学习功能。我在一个场景中感到困惑。 假设我有三个功能

<script>
var fnRef = function() { 
  console.log("i'm function with no name but refered to fnRef"); 
}; 

var funRef2 = function test() {
  console.log("im test reffered to funRef2");
};

function test2() {
  console.log("i'm test2 named function")
};
</script>

fnReffnref2test2将作为属性分配给窗口,fnReffnRef2是可变的,test2已命名充当变量的函数。 但是当test2提到时,为什么funref2没有分配给全局对象(窗口)?为什么我无法执行test();,有人可以告诉我详细情况。

1 个答案:

答案 0 :(得分:4)

named function expression非常有用,因此您可以在不使用arguments.callee的情况下访问其自身范围内的函数,并且在调试时也可以更轻松,因为在堆栈跟踪中可以看到名称,断点等。

这个名称只对函数bodys范围是本地的,意思是

var test1 = function test2() {

   if (something) test2(); // available in this scope only

}

test2(); // not here

您不能通过它的名称来调用该函数,只能通过它所分配的变量来调用该函数,因为函数名称仅限于函数表达式时的函数范围

定义function declaration时,名称将分配给当前范围并提升,因此

var bar = test();

function test() { return 'foo'; }

或多或少变成了这个

var test = function() { return 'foo'; }

var bar = test();