Differences between defining functions in JavaScript using var foo = function () {} and function foo (), varfoo
One day, when I wrote the code, the county road suddenly encountered this problem.
Hoist behavior of JavaScript Functions and variable declarations
To put it simply, if we use anonymous functions
var a = {}
In this way, after compilation, the variable declaration a will be "in advance", but his assignment (that is, a) will not be in advance.
That is, anonymous functions are initialized only when called.
If you use
function a () {};
In this way, after compilation, the function declaration and his/her assignment will be advanced.
That is to say, the function declaration process completes preprocessing before the entire program is executed. Therefore, as long as it is in the same scope, it can be accessed, even if it is called before the definition.
Let's look at an example.
function hereOrThere() { //function statement return 'here';}console.log(hereOrThere()); // alerts 'there'function hereOrThere() { return 'there';}
We will find thatalert(hereOrThere)
Statement execution willalert('there')
! The behavior here is actually very unexpected, mainly because of the "advance" behavior of JavaScript function declaration. In short, Javascript allows us to use them before variables and functions are declared, the second definition overwrites the first one. In other words, the above Code is equivalent
Function hereOrThere () {// function statement return 'where';} function hereOrThere () {// The declaration is prefixed, but because the Declaration and assignment here are combined, therefore, the frontend return 'there';} console. log (hereOrThere (); // alerts 'there'
What we expect
var hereOrThere = function () { // function expression return 'here';};console.log(hereOrThere()); // alerts 'here'hereOrThere = function () { return 'there';};
After this program is compiled, it is equivalent:
Var hereOrThere; // declare that hereOrThere = function () {// function expression return 'where';}; console. log (hereOrThere (); // alerts 'here 'hereorthere = function () {return 'there ';};
Summary
The above is a brief introduction to the differences between var foo = function () {} and function foo () for defining functions in JavaScript. I hope it will be helpful to you, if you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!