Various common methods of function definition in JavaScript

  • 2020-03-30 03:58:27
  • OfStack

This article describes in detail the various common JavaScript function definition methods, to share with you for your reference. Specific analysis is as follows:

First, take a look at the four most common function definitions in JavaScript:

The Function defined by the Function constructor is as follows:


var multiply = new Function('x', 'y', 'return x * y;');

Function declaration, which is the most common way:


function multiply(x, y) {
  return x * y;
}

Function expressions, declared as anonymous functions and then assigned to a variable, are very common:


var multiply = function(x, y) {
  return x * y;
}

Function expression, but the function declaration assigns a value to a variable as a named function, which looks exactly like the same way:


var multiply = function multi(x, y) {
  return x * y;
}

First of all, let's compare the function name and the direct relationship between the function variable to which the function is assigned. For example 4, the relation between multiply and multi is as follows:

Function names cannot be changed; instead, function variables can be reassigned. It should be easy to understand that function variables can be reassigned. In the fourth example, we just defined the variable multiply.


multiply = function(x, y) {
  return x + y;
}

Immediately, I went from multiplying to adding. However, it is impossible for the function variable multi to change. The function definition is already there. As long as we keep the reference, it will not change.

Function names cannot be used outside the function, it is only visible inside the function body, a very simple example:


var foo = function bar() {
  alert('hello');
}
foo(); //The "hello" string is prompted
bar(); //Execution error, bar undefined

Obviously, the bar here is really a function name, but it really can't be called externally. At this time, there must be children's shoes to ask why. This example still looks so lovely, the same as example 4. Why not use example 2? Good question. Let me break it down.

Continuing with example 4, we can see that the function name (multi) and the function variable (multiply) are not the same. With that said, I think the four examples above can be reduced to three, and example 2 and example 4 should be essentially the same. What? No? Hee hee, I still have to keep in suspense ~ keep reading ~~

We find that compared with example 2 and example 4, only the function variable of var is missing, while compared with example 3 and example 4, only the function name is missing. Here, the essence of example 2 and example 4 is the same in terms of phenomenon. The irrefutable evidence is as follows:


function foo() {}
alert(foo); //The prompt contains the function name of "foo"
var bar = foo;
alert(bar); //The prompt still contains only the function name of "foo" and has nothing to do with bar

Is that hard evidence? Is the above example 2 code written in combination with the example 4 code? Right, this is what I just said the two essence should be the same, just in case 2 way defined function, JS engine to help us do some things, such as a declared function called multiply function, at the same time also quietly defines a variable, also called multiply and then assigned to this variable, two exactly the same name, we thought at the time of using the function name multiply, is actually in use multiply this function variables, dizzy ~ to be honest, I'm dizzy ~ ~ anyway when we call, just use function variable called, A function name cannot be called externally, so here's my inference.

But one small difference here is that a function declared in a way that is different from a constructor or a function expression is declared in a way that is called before the function is defined... Don't say, or look at the code:


foo(); //Prompt Foo
function foo() {
  alert('Foo');
}
bar(); //Dude, it's not the same as up there, don't try to be brave, is that wrong? Bar is not defined
var bar = function() {
  alert('Bar');
}

The constructor declaration of the function, so the declaration of the function will not inherit the current declaration location scope, it will only have the default global scope, however, this is the other several function declaration methods also have, as follows:


function foo() {
  var hi = 'hello';
  //return function() {
  //  alert(hi);
  //};
  return Function('return hi;');
}
foo()(); //The execution effect everybody runs to see by oneself

As you might expect, the execution of the function returned by the constructor declaration must report an error because the hi variable is not in its scope (that is, the global scope).

The other thing is that it's common to say that a function declared in a constructor way is less efficient, why is that? Today we know from the documentation that because the other three methods of declaring functions are parsed only once, they actually exist in closures, but that's only related to the scope chain, the body of the function is parsed only once. But the constructor way is, every time you execute a function, the body of the function is parsed once, and if you think about it this way, the function is an object that contains the parameters and the body of the function, and every time you execute it, you have to parse the parameters and the body of the function, and then it's executed, which is inefficient. Don't know how to do the specific experiment?

Finally, one of the things that no one pays much attention to is when the way a function is declared is not the way a function lives.

When it's part of an expression, it's like example 3 and example 4.
It is no longer the script itself or the "source element" of the function. What is a source element? A "source element" is A non-nested statement in the script or A function body.


var x = 0;        // source element 
if (x == 0) {      // source element 
  x = 10;        //Not a source element because it's nested in an if statement
  function boo() {}   //Not a source element because it's nested in an if statement
} 
function foo() {     // source element 
  var y = 20;      // source element 
  function bar() {}   // source element 
  while (y == 10) {   // source element 
   function blah() {} //Not a source element because it's nested in a while statement
   y++;        //Not a source element because it's nested in a while statement
  } 
}

Now that the concept of source element is understood, let's continue with the function declaration.


//Function declaration
function foo() {} 
  
//Functional expression
(function bar() {}) 
  
//Functional expression
x = function hello() {} 
 
if (x) { 
  //Functional expression
  function world() {} 
}
 
// function statement 
function a() { 
  // function statement 
  function b() {} 
  if (0) { 
   //Functional expression
   function c() {} 
  } 
}

Finally here on my own understanding, the reason for the difference between a function declarations and a function declaration, because I saw, in the way of function declaration of the function definition, at the time of JS parsing engine performs its statement in advance, that is, as we have just said above can be used before the function definition, is actually a parsing engine before we use has its resolution, but the function declarations, like the expression function declarations, JS parsing engine will only define the variables var statement in advance, the variable value is undefined, the real value assigned to this variable is the actual location in the code, So the error reports mentioned above are undefined, the actual variable is defined, but not assigned yet, and the JS parsing engine does not know it is a function.

I believe that this article described the javascript WEB program design has a certain reference value.


Related articles: