Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - Difference between assigning function to variable or not

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

The first:

function testFunction(){

};

The second:

var testFunction = function (){

};

Is there a difference between these?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() {};

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;

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...