将函数分配给变量与否之间的区别 [英] Difference between assigning function to variable or not

查看:236
本文介绍了将函数分配给变量与否之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a worked on a couple different projects and I have seen two different ways of creating jQuery/JavaScript functions.

第一个:

function testFunction(){

};

第二种:

var testFunction = function (){

};

这些之间有区别吗?

推荐答案

主要区别在于第一个(函数声明)悬挂到顶部声明它的范围,而第二个(函数表达式)不是。

The main difference is the first one (a function declaration) is hoisted to the top of the scope in which it is declared, whereas the second one (a function expression) is not.

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

This is the reason you are able to call a function that has been declared after you call it:

testFunction();
function testFunction() {}

你不能用函数表达式做到这一点,由于分配是就地发生的:

You can't do that with a function expression, since the assignment happens in-place:

testFunction();
var testFunction = function() {}; //TypeError

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

There is also a third form (a named function expression):

var testFunction = function myFunc() {};

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

In this case, the identifier myFunc is only in scope inside the function, whereas testFunction is available in whatever scope it is declared. BUT (and there's always a but when it comes to Internet Explorer) in IE below version 9 the myFunc identifier wrongly leaks out to the containing scope. Named function expressions are useful when you need to refer to the calling function (since arguments.callee is deprecated).

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

Also note that the same is true for variable declarations:

console.log(x); //undefined (not TypeError)
var x = 10;

您可以想象JavaScript引擎会解释如下代码:

You can imagine that the JavaScript engine interprets the code like this:

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

这篇关于将函数分配给变量与否之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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