将函数分配给变量与否之间的区别

dan*_*tch 33 javascript jquery

我参与了几个不同的项目,我已经看到了两种创建jQuery/JavaScript函数的方法.

首先:

function testFunction(){

};
Run Code Online (Sandbox Code Playgroud)

第二:

var testFunction = function (){

};
Run Code Online (Sandbox Code Playgroud)

这些之间有区别吗?

Jam*_*ice 50

主要区别在于第一个(函数声明)被提升到声明它的作用域的顶部,而第二个(函数表达式)则没有.

这就是你能够在调用之后调用已声明的函数的原因:

testFunction();
function testFunction() {}
Run Code Online (Sandbox Code Playgroud)

您不能使用函数表达式执行此操作,因为赋值是就地发生的:

testFunction();
var testFunction = function() {}; //TypeError
Run Code Online (Sandbox Code Playgroud)

还有第三种形式(命名函数表达式):

var testFunction = function myFunc() {};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,标识符myFunc仅在函数内的范围内,而testFunction在声明的任何范围内都可用.但是,在版本9以下的IE中,myFunc标识符错误地泄漏到包含的范围内(并且总是存在但是当涉及到Internet Explorer时).当您需要引用调用函数(因为arguments.callee不推荐使用)时,命名函数表达式很有用.


另请注意,变量声明也是如此:

console.log(x); //undefined (not TypeError)
var x = 10;
Run Code Online (Sandbox Code Playgroud)

您可以想象JavaScript引擎会像这样解释代码:

var x; //Declaration is hoisted to top of scope, value is `undefined`
console.log(x);
x = 10; //Assignment happens where you expect it to
Run Code Online (Sandbox Code Playgroud)

  • +1***知识***我不知道这是怎么回事.我遇到了`var testFunction = function(){}`的问题,并且不知道为什么.这完全有道理. (9认同)