A variety of common function definition methods for JavaScript _javascript tips

Source: Internet
Author: User
Tags function definition

This article details the JavaScript of various common function definition methods, share for everyone to reference. The specific analysis is as follows:

First take a look at four of the most common function definitions of javascript:

Functions defined with function constructors, the code is as follows:

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

function declaration, this is also the most common one:

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

A function expression, declared as an anonymous function and then assigned to a variable, is a common way:

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

function expression, but the function declaration is to assign a variable to a named function, and it looks like the same way:

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

First, compare the function name, and the function assigned to the function variable direct relationship, really around ... Intuitively a little, from just example 4, that is multiply this function variable and multi This function name relationship:

Function names cannot be modified, and conversely, functions can be assigned again. The function variable can be assigned to the value should be well understood, our 4th example just defined the multiply this variable, see it is not pleasing to the eye, the value of the re-assignment:

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

Immediately changed from multiplication to addition. But multi this function variable is impossible, the function definition is already there, as long as it retains its reference, it will not change, may not be very good understanding here, think first, look down, slowly should be able to understand.

The function name cannot be used outside the function at the same time, it is only visible inside the function body, a very simple example:

var foo = function bar () {
  alert (' Hello ');
}
Foo (); Prompt "Hello" string
bar ();//execute error, bar not defined

And obviously, the bar here is really a function name, but it really can't be invoked externally. At this time there will be children's shoes to ask why this example is still so well-behaved, and example 41 samples, how not use case 2 of the way? Good question, and listen to me slowly decompose.

To continue with example 4, we can see that the function name (multi) and the function variable (multiply) are not the same, in fact, there is no relationship between the two, so there is no need for consistency. Speaking of which, I think the above 4 examples should be reduced to 3, and the essence of Example 2 and 4 should be consistent. What, don't believe it? Xi hee, I have to continue to suspense ha ~ continue to read ~ ~

We found that, compared with example 2 and example 4, the function variable of Var was only less, and the example 3 compared with example 4, except that the function name was less, and here from the phenomenon, example 2 and 4 are the same in nature, and the evidence is as follows:

function foo () {}
alert (foo);//Prompt contains "foo" for the name
var bar = foo;
alert (bar); The hint still contains only the function name "foo" and there is no relationship between bar and half cents.

Is it true? The above example 2 code combined to write is not the way to precedent 4? Correct, this is what I just said the two nature should be the same, just use case 2 way to define a function, JS engine to help us do some things, such as declaring the function named multiply function, but also quietly defined a also called multiply variables, and then assign to this variable, Two exactly the same name, we think that in the use of the function name multiply, the actual is in the use of multiply variable, dizzy it ~ to tell the truth, I was dizzy ~ ~ In short we call, really use function variable call, and function name is unable to call function outside, So I have the above inference.

But here's a little bit of a difference, the function declaration method defines a function that differs from a constructor declaration or a function expression declaration in that a function declaration method can be invoked before the function definition ... Don't say, or look at the code:

Foo (); Prompt foo
function foo () {
  alert (' foo ');
}
Bar (); Dude, it's not the same as the above, don't be a hero, it's not an error? Prompt bar does not define
var bar = function () {
  alert (' Bar ');
}

Again, a function declared by a constructor that declares a function that does not inherit the scope of the current declaration location, which by default will only have global scope, but this is also the case for several other function declarations, as follows:

function foo () {
  var hi = ' Hello ';
  return function () {
  //  alert (HI);
  //};
  Return Function (' return hi; ');
}
Foo () (); Executive effect everybody run and see for yourself.

As you can imagine, this function returned with a constructor declaration performs an inevitable error because there is no hi in the scope (that is, the global scope).

Another point is that it is often said that the constructor method declares a function of low efficiency, which is why? Today the document is learned because the other 3 ways of declaring functions will only be parsed once, in fact they exist in the closure, but that is only related to the scope chain, the function body is only parsed once. But how does the constructor function, each time the function is executed, its function body is parsed once, so we can think of this declared function is an object, which holds the parameters and function body, each time the execution must parse first, the parameter and function body, will execute, this necessarily inefficient. Specific experiments do not know how to do?

Finally, a place where we don't pay much attention to, when it looks like the way the function is declared is not a function of life (or so around ~ simple, that is, example 2 of the way when inadvertently in another way):

When it becomes part of an expression, it is like Example 3 and Example 4.
is no longer the script itself or the source element of the function. What is the source element? That is, a non nested statement in the script or a function body (a "source element" is a non-nested statement in "script or A), for example:

var x = 0;        SOURCE element 
if (x = = 0) {      //source element 
  x = ten;        Not a source element because it is nested within the IF Statement
  function Boo () {}   //Not a source element because it is nested within the IF statement
} 
function foo () {     //source element 
  var y =;      SOURCE element 
  function bar () {}   //source element while 
  (y = = ten) {   //source element 
   Functio n blah () {}//not a source element because it is nested within a while statement
   y++;        Not a source element because it is nested within the while statement
  } 

The concept of the source element probably has the understanding, continues just to say the function declaration, see:

function declaration functions
foo () {} 
  
//function expression
(function bar () {}) 
  
//function expression
x = Functions Hello () {} 
 
if ( x) { 
  //function expression function World
  () {} 
}
 
//Function statement 
function A () { 
  /function Statement 
  function B () {} 
  if (0) { 
   //function expression
   function C () {}} 
}

And finally, here's my own understanding, the reason to differentiate between function declarations and non function declarations is that, in my view, the function definition of the function declaration method will be declared in advance when the JS parsing engine executes, which, as we just said, can be used before the function definition, Actually, the parsing engine has parsed it before we use it, but a non function declaration, just like the expression function declaration, the JS parsing engine will only define the variables in the Var declaration in advance, at which point the variable value is undefined, and the actual assignment to the variable is where the code actually resides, Therefore, the above mentioned error is undefined, the actual variable has been defined, but has not been assigned a value, JS parsing engine does not know it as a function.

It is believed that this article has a certain reference value for everyone JavaScript Web programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.