JavaScript series----functions (function) Chapter

Source: Internet
Author: User
Tags abstract definition

1. Functions

The definition of a function in the mass-user is this: a function is an event-driven or reusable block of code that executes when it is invoked.

Admittedly, we don't get anything of value from this abstract definition. Here are some examples of how a function can be defined:

function Add (NUM1, num2) {
  return NUM1 + num2;} var add = function (NUM1, num2) {  return num1 + num2;} This is the more common two kinds of  

The following two species are relatively rare
var add=new Function ("Num1", "num2", "return num1+num2");
var add=function ("Num1", "num2", "return num1+num2");

The above four methods are the correct syntax for creating a function. However, the common is generally the first two types. Because there are some flaws in the latter two compared to the first two types.

  1. The latter two kinds of comparison cumbersome and not intuitive. This can be seen in the above example.
  2. There are some fatal flaws in the latter two. This function is created in such a way that it is not possible to maintain a chain of scopes that are part of a function, and the functions created at any time under the new function are equivalent to those created under the global scope. This can be demonstrated in the following example.
    var x = 1; var add = (function () {  var x = +;  return function (num) {    return num + x;  }} ()); Console.log (Add (0));//100    
    var x = 1; var add = (function () {  var x = +;  return new Function (' Num1 ', ' return num1+x ');} ()); Console.log (Add (0));//1   

    In other words, the latter two ways of creating a function cannot form a complete chain of function scopes (which will be discussed later), and there can be no so-called closures.

  3. The latter two are too inefficient to operate.
    First of all, JS is not efficient for parsing strings, and there are a lot of strings in the (new) function.
    Secondly, JS interpreter, for use function () {}, this form of functions, have some form of optimization. Like the following.

    var array = [
    ];
    for (var i = 0; i <; i++) {
    Array[i] = function () {
    return ' undefined ';
    }
    }//the first Kind


    var array = [
    ];
    for (var i = 0; i <; i++) {
    Array[i] = new Function ("return undefined");
    }//the second kind,

there is a big gap between these two approaches in operational efficiency. For, the first one only needs to execute once function () {}, the other 999 times is an assignment, and then a function to execute 1000 times to create and assign a value.

It is because of the three reasons on three sides that the function () {} is more prevalent in this way.

In addition, you may have seen the following, but this form is only a variant.

var New function () {  return 1 + 2;}; Console.log (typeof  add);//objectvar result = add.constructor ();/* The call must be made in this way */console.log (result);//3

In this form, the new function () is created essentially using an anonymous function to create an object. A constructor property of this object just points to its constructor, which is the anonymous function. So it's actually an ugly way of writing.

Here, we are just describing a few ways to define a function. By comparison, we know the first two are more practical, but even so, there is a huge difference between the first and second definitions. In the next section, we'll go on to the difference between the two ways.

2. Function declarations and function expressions

  function declaration:

   function function name ( parameter: Optional ) { body }

 function expression:

   function name (optional)( parameter: Optional ) { function body }

So, it can be seen that if the function name is not declared, it must be an expression, but if the function name is declared, how to determine whether it is a function declaration or function expression? ECMAScript is distinguished by context, if function foo () {} is part of an assignment expression, it is a function expression, if function foo () {} is contained within a function body, or at the top of the program, Then it is a function declaration.

So, as we can see, the first two ways to create functions are function declarations and function expressions, respectively.

function Add (NUM1, num2) {  return num1 + num2;} function declares  var function (NUM1, num2) {  return num1 + num2;} //function expression

  In addition, there are some function expressions that are more easily confused with function declarations.

(function  Add (NUM1, num2) {  return num1 + num2;}); //function expression 
var add = function foo (NUM1, num2) {  return num1 + num2;} function Expression  

  () in the JS language rule is a grouping operator, according to the standard group operator in the code will be implicitly considered an expression.

And the following one is more interesting, the left side of the assignment expression is a function, about this point different parser on the processing of this is different, some think this is a function declaration, some think this is a function expression, different parser on the processing of this is not the same.

However, currently the default function expression on the mainstream browser, and Foo as the function identifier, only within its function can be recognized. Look at the following example:

var add=function  foo (n) {  if(n==1)return 1;   Else return N+foo (n-1);}; Console.log (Add (3));//6console.log (foo (3));//error, Foo is not defined

So what's the difference between a function declaration and a function expression?

Answering these questions involves the case when the function is called.

3. Execution environment and scope of functions                    

As we all know, the function runs in the newly opened stack. So what is the execution environment of the code when the function is run?  

What happens when a function is called? 

function Add (NUM1, num2) {  var num3 = +;   return NUM1 + num2 + num3;} var result = Add (+); Console.log (result);

This section of code will invoke the Add function we declared when it executes to line 5th, and the Add function will do the following when it is called:

The declaration of the 1.add function parameter and assigns a value.

Declaration of a function within a 2.add function (if the function variable has the same name as a variable of a function parameter, the function declaration overrides the formal parameter declaration).

Declaration of variables within the 3.add function. -----> functions are executed sequentially.

Here are a few examples to prove that:

Example one: the declaration of a function within a function overrides the declaration of a function parameter.

function Add (NUM1, num2) {  console.log (typeof  num1);//function
function Num1 () {}
var result = Add (100, 200);

Example two: declaration of a variable within a function does not override the declaration of formal parameters and functions within functions

function Add (NUM1, num2) {  console.log (typeof  num1);//number   var num1 = "All";   } var result = Add (100, 200);

Add:

The so-called variable declarations are similar to Var x, y; This situation. and Var x=1;

is actually var x; x=1; two-step execution.

Variable declarations are always like this: Var x;

Execution environment of the function:

By the above we know that the function executes when a new stack is created, while the stack holds the variables declared inside the function, and the values of the variables are assigned according to the three steps just discussed before the function code is run. That is, when a function is called, all the variables necessary to run the function are already present in the stack before the code runs. These variables together make up the execution environment of the function.

If the interpreter really puts all the declarations inside the function on the stack, then the interpreter should be able to determine the size of the stack space when the stack is opened. However, if the size of the stack space is determined later, there are several issues that need to be addressed:

    • The type of the variable is changed at run time. The size of the stack space needs to be constantly adjusted.
    • Each function maintains its own scope chain at the time of declaration, and if the variable type on the scope chain, it needs to adjust the stack on the whole scope chain.
    • You need to rewrite the garbage collection mechanism (tag-cleanup is not applicable) for this structure.

Improvement: Introduction of function variables

When a function is called, the declaration of the variable is not saved in the stack, but in an object. Instead, the reference to the object is saved in the stack. This object is stored in the heap and works as follows:

function Add (NUM1, num2) {  var num3 = +;   return NUM1 + num2 + num3;} var result = Add (100, 200);

When a function is called (before it is executed), the interpreter creates a AddReference object:

addreference={

num1:100;

num2:200;

num3:undefined;

};

The reference to the AddReference object is pressed into the stack, and the object itself is present in the heap.

Add:

Function at run time, the stack also holds the return value and the this pointer. When the function execution is exited, the stack is emptied, and if there is a function that references this function variable, the function variable is added to the scope chain of the reference function, otherwise the function variable is deleted if the garbage collection mechanism does not find a reference to the function variable.

After improvement:

    • The size of the stack space is determined: Before the function is run, the space required by the stack can be determined. There are only three elements: the this pointer, a reference to the function variable, and a return value. (The return value is also stored in a variable, managed by the interpreter)
    • Function at run time, if a new function is created. You only need to add the function variable object to the scope chain of the new function.
    • It is only necessary to manage memory based on whether the reference count for this function variable is 0, without overriding the garbage collection mechanism.

4. Scope chain                     of functions

In the third part we discuss that function variables are stored in the scope of the function. Let's use this example to illustrate this phenomenon.

1 varFun ;2(functionfun1 () {3   varx = 1;4(functionfun2 () {5     vary = 2;6Fun =function () {7       returnX +y;8     }9   }());Ten }()) One  A varresult=Fun (); -Console.log (Result)//3

According to the example above, what happens when we analyze the function execution?

  1. The variable object in the global scope.
    Globalreference = {
    ...//pre-existing objects such as object,math,date such as fun:undefined; result:undefined;}
  2. When the function runs to the second row, the FUN1 variable object
    Fun1reference = {  x:undefined;}

    when you execute to line 4th,
    Fun1reference = {
    X:1;
    }
    Scope chain of FUN1: Globalreference
  3. When the function runs to the fourth row, the variable object of FUN2
    Fun2reference = {  y:undefined;}
    when you execute to line 5th,
    Fun2reference = {
    2;
    }
    FUN1 scope chain: globalreference--->fun1reference
  4. When the function runs to line 6th, the scope chain of fun
    Fun scope chain: globalreference--->fun1reference--->fun2reference
  5. Fun2 execution is completed--->fun1 execution of the stack.
  6. The fun is called when the function runs to the 12th row.
                        Globalreference = {                                |        .......                                |       fun:undefined;                                |        result:undefined;                                | } fun1reference ={x:1;} | | | |                                 fun2reference={y:2} | | | |  funreference:{}; 
  7. Fun execution finished, result=6;13 line, output results.


Above, we have simulated the process of executing the function once. Let's take a look at the global scope object.

First, make it clear that the global scope is also a variable object.

Globalreference = {object  : Built-in object constructor object;  Array: Built-in arrays constructor object;  Function: Built-in functions constructor object;  Math: Built-in math object;  Date: Built-in constructor object;  .......;  Window:globalreference}

The Window object maintains a reference to the global object.
  Add: The code executed under the console is executed in the eval () function, which can be used and can change the execution environment in which the current function is located.

5. The difference between                     a variable and an object

1. Variables : The amount that can be changed. Only the ability to precede the Var (non-function) is called a variable. The function has its own unique variable declaration method.   

var x = 1,y = 2; var z = 3;
Like the above is the variable

xxx=1;//This is not a variable, this is the form

2. Properties : A variable within an object.

var object={
X:1, y:2, Z:3}; X, y, Z are attributes.

Both of the above are easy to distinguish, but how do you explain the following?

is rest=1;//rest a property or a variable?

This sentence is generally in the function execution time, often encountered, so write a great disadvantage.

    1. Find slower. There is no Var in front of rest, it is definitely not a variable. Then, at execution time, it will look up along the scope chain until the variable object is in the global scope. is not found at this time, it is used as a property of the global scope variable object according to the rule.

2. Changed the global scope variable object. In general, we should try to avoid changing global scope objects when executing code.

That is, if we use a "variable" with no previous Var, the "variable" will be used as the property of the global scope variable during execution.

3 . Differences between variables and attributes:

    • The property, which is configured for deletion, can be deleted by the object on which it resides.

Like what:

var object={x:1}Delete//truey=2; Delete window.y (or delete y); //
    • A variable is declared as a property of a function variable. It can be deleted in principle, but because we cannot get the object of the function variable (window is a special case), it is impossible to delete it in the actual operation.
    • Variables are generally for the declaration period, whereas properties are generally for the execution period. The two are essentially different in meaning.
    • Finds the properties of a normal object and does not throw an error if it is not found. However, finding the properties of a variable object throws an error if it is not found.
      var Object = {};console.log (object. z);//undefined,-----find Console.log in normal variable (WINDOW.V) ;//undefined-----Find Console.log (z) in common variables;//error;           The-----is found in the variable object on the scope chain, and the error is not located.   

JavaScript series----functions (function) Chapter

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.