JS two ways of definition of the difference the internal principle

  • 2020-03-29 23:55:46
  • OfStack

I believe you've used both, but not everyone knows the difference, the inner workings.
 
//Method 1
function func1(x,y){ 
// your code 
} 
//Way 2
var func2 = function(x,y){ 
// your code 
} 

Mode 1 is a typical Function declaration.
Method 2 is a Function expressions, which assigns an anonymous Function to a variable. Or another way is to create an anonymous function with a formal parameter of x and y, and then assign that anonymous function to the variable func2.

The main differences are as follows:
1, function declares the name of the specified function to be displayed, here is func1; Function expressions use anonymous functions
2. Mode 1 is loaded into the scope before the code is executed (interpretation period), while mode 2 is loaded when the code is executed (runtime)

A simple example illustrates the difference in their use
 
alert(func1); //-> Func1 source
alert(func2); // --> undefined 
//Method 1
function func1(x,y){ 
// your code 
} 
//Way 2
var func2 = function(x,y){ 
// your code 
} 

As you can see, the first time the source of func1 pops up, the second time it's undefined. That is, method 1(function declaration) is used to define the function, which can be used on the function code, and method 2(function expression) is used to define the function, which cannot be used before its definition, but only after its definition.

Internally, it involves the Execution context and Activation object. For more information, read the EcmaScript 5 documentation.

Recently, I have found that more and more people prefer to use method 2 to define functions, especially in nested functions. Like simply defining a function individual or custom 1.

Related articles: