JS declaration function (function creation) detailed

Source: Internet
Author: User
Tags function definition

In general, when we write JavaScript, we like to first name an empty function (such as code 1), I feel this will consume some performance, and the code is written more. You can actually declare the function you want to write without first declaring an empty function (such as code 2).

JavaScript definition functions (declaring functions) can have three methods: Normal method, constructor, function direct quantity.

The simplest way to declare JavaScript functions is no different from our other programming languages, function (param) {}

The code is as follows Copy Code


Code 1:

function MyFunction () {
This.mymethod = function () {}
}
var myObject = new MyFunction ();

Code 2

var myObject = {
Mymethod:function () {}
};


If the function does not contain a return statement, only the function body statement is executed and returns the undefined

Constructor method: new function ();

The code is as follows Copy Code


To define a JavaScript function in the form of a constructor
var add = new Function (' A ', ' B ', ' return a+b; ');


The code above may be very simple and you will not be able to read it.


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

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

The code is as follows Copy Code

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

2. function declaration, this is also the most common one:

The code is as follows Copy Code

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

3. function expressions, declared as anonymous functions and then assigned to a variable, a very common way:

The code is as follows Copy Code

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

4. function expression, but function declaration for a named function to assign a value to a variable, it looks like the same way:

The code is as follows Copy Code

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:

The code is as follows Copy Code

◦ function names cannot be modified, and conversely, function variables 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:

The code is as follows Copy Code

var foo = function bar () {alert (' Hello ');} foo (); Prompt "Hello" string bar (); Error executing, 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.

◦ Continues with Example 4, we can see that the function name (multi) and 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:

The code is as follows Copy Code

function foo () {} alert (foo);
Prompt for function name containing "foo"
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:

The code is as follows Copy Code

Foo (); Tip 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? Hint bar not defined
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:

The code is as follows Copy Code
function foo () {
var hi = ' Hello ';
return function () {
Alert (HI);
//};
Return Function (' return hi; ');
}
Foo () ();

Executive effect everybody run and see for yourself.

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):

◦ As part of the expression, as in 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:

The code is as follows Copy Code
var x = 0; SOURCE element
if (x = = 0) {//source element
x = 10; 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 = 20; SOURCE element
function bar () {}//source element
while (y = = ten) {//source element
function 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:

  code is as follows copy code
//function declaration
Function foo () {}  
   
//function Expression
(function Bar () {})   
   
//function expression
x = function Hello () {}  
  ;
if (x) {  
  //function expression
   function world () {}  
}
 
//function statement  
Function A () {  
  //function statement  
   function B () {}  
   if (0) {  
      function expression
      function C () {}  
  }  
}

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.

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.