Functions and closures

Source: Internet
Author: User

an overview1.1 function Declarations

(1)function command

A function is a block of code that is named with a function command to facilitate repeated invocation. This declarative approach is called function Declaration.

function print () {  //  ...}

(2) function Expression

In addition to declaring functions with a function command, you can also use variable assignment notation.

var function  (){  // ...};

This notation assigns an anonymous function to the variable. At this point, the anonymous function is also called a function expression, because the assignment statement can only put an expression to the right of the equal sign. When you declare a function with a function expression, the function command does not have a functional name. If the function name is added, it becomes a local variable inside the function, valid only inside the function body, and is not valid outside the function body.

var function x () {  console.log (typeof//  referenceerror:x is not defined   //  function

(3) Function constructor

There is also a third way to declare a function: through a function constructor declaration. If there is only one argument, the argument is the body of the function.

var New Function ("x", "Y", "Return (x+y)"); // equivalent to defining the following function // function Add (x, y) {//   return (x+y); //  }

1.2 Return Statement

When the JavaScript engine encounters a return statement, it directly returns the value of the expression after return, which is not executed even if there are any statements. That is, the expression that the return statement takes is the return value of the function. The return statement is not required, and if not, the function returns no value, or returns undefined.

1.3 First class citizens

JavaScript functions are equal to other data types, and functions can be used where other data types are used. For example, you can assign a function to a property of a variable and an object, or it can be passed as a parameter to another function, or returned as the result of a function. This means that the function is equal to the other data types, so the function is called the first class citizen.

function Add (x, y  ) {return x+y;} // Assign a function to a variable var operator = add; // use functions as parameters and return values function A (OP) {  return  op;} A (add) (//  2

1.4 Promotion of function names

  The JavaScript engine takes the function name as the variable name, so when declaring a function with the functions command, the entire function is promoted to the head of the code. Therefore, the following code does not error:

f (); function f () {}

On the surface, the above code seems to call the function f before declaring it. But in fact, because of " variable elevation ", the function f is promoted to the head of the code, which is declared before the call. However, if you define a function with an assignment statement, JavaScript will give you an error:

f (); var function // typeerror:undefined is not a function

The above code is equivalent to:

varfunction () {};

 When F is called, F is only declared, not yet assigned, equals undefined, so it will be an error. Therefore, if you declare the same function with both a functions command and an assignment statement, the definition of the assignment statement is always used.

var function () {  console.log (' 1 ');} function f () {  console.log (' 2 '//  1

1.5 The case of a function cannot be declared

  function declaration statements are not real statements, the ECMAScript specification simply allows them to be the top-level statement. They can appear in global code, or embedded in other functions, but they cannot appear in loops, conditional judgments, or try/catch/finally, and with statements.

1.6Name Property

  Most JavaScript engines support non-standard name attributes. This property returns the name of the function immediately following the Functions keyword.

function//  ' F1 'varfunction//   ' varfunction//  ' MyName '

In the above code, the function's Name property always returns the name of the function immediately after the function keyword. For F2, returning an empty string, for F3, returns the name of the function expression (the real function name or the F3,myname name is only available inside the function body).

2. Arguments and formal parameters of a function2.1 Length Property

all functions have a length property that returns the number of arguments in the function definition. the Length property provides a mechanism for determining the difference in parameters when defining and invoking, so that object-oriented programming can be implemented as a "method overload" (overload).

function//  2

The above code defines an empty function f, whose Length property is the number of arguments defined. The length property is always equal to 2 regardless of the number of arguments entered at the time of invocation.

2.2 Omitting of parameters

Parameters are not required, JavaScript language allows omitting parameters.

function F (A, B    ) {return  A;} F (//  1//  1//  undefined//  2 

The function f of the above code defines two parameters, but the runtime does not give an error regardless of how many arguments are supplied (or if no arguments are supplied). the value of the omitted parameter becomes undefined. It is important to note that the length property of the function is independent of the number of arguments actually passed in, reflecting only the number of arguments at the time of definition.

However, there is no way to omit only the previous parameters, but to retain the back parameters. If you must omit the previous argument, only explicitly pass in the undefined.

2.3 Method of transmitting parameters

The function parameter of JavaScript is passed as a pass-through value (passes by value), which means that the parameter values are modified in the body of the function without affecting the outside of the function.

// modifying the parameter values of the original type var p = 2function  f (p) {    = 3//  2//  Modifying the parameter value of a composite type var o = [n/a]; function F (o) {    = [2,3,4//  [1, 2, 3]

The above code is divided into two segments, modifying the parameter values of the original type and the parameter values of the composite type, respectively. In both cases, modifying the parameter values inside the function does not affect the outside of the function.

need very note , although the parameter itself is a pass-through value, However, for a variable of a compound type, the property value is a pass by reference, that is, the property value is read by address. Therefore, modifying the property value of a compound type variable in the function body affects the outside of the function.

// modifying an object's property values var o = {p:1 }; function f (obj) {    = 2//  2/ / Modify the property value of an array var a = [A. ]; function F (a) {    a[0]=4//  [4,2,3]

The above code, in the body of the function, modifies the property values of the object and array respectively, and the result affects the outside of the function, which proves that the property value of the compound type variable is the transfer of the address.

In some cases, it can be written as a property of a global object if it is necessary to achieve a pass-through effect on a variable.

var a = 1; function f (P) {    window[p]=2;} F (' a '//  2

2.4 Variable-length argument list arguments object

The ECMAScript function does not mind passing in the number of arguments, and does not care about what type of arguments are passed in, because the arguments in the ECMAScript are represented by an array, and this number is arguments. The arguments object contains all parameters when the function is run, Arguments[0] is the first argument, Arguments[1] is the second argument, and so on. This object can only be used if it is inside the function body.

var function (one) {  console.log (arguments[0]);  Console.log (arguments[1]);  Console.log (arguments[2]);} F (1, 2, 3)//  1//  2//  3
View Code

The arguments object can also be assigned a value (strict mode does not allow this usage) in addition to the parameters that can be read. You can judge a function call with a few arguments by arguments the length property of the object.

(1) Relationship to arrays

  It is important to note that although the arguments is much like an array, it is an object. Some methods for arrays, such as the slice and foreach methods, cannot be used on arguments objects. However, sometimes arguments can be used like arrays in some methods that are used only for arrays. For example, use the Apply method, or use the Concat method to complete an array merge.

// for the Apply method myfunction.apply (obj, arguments). // use merge with another array Array.prototype.concat.apply ([i], arguments)

(2) Caller and callee

The arguments object has a callee property that returns the original function it corresponds to.

Internal properties of the function arguments and this

Functions and closures

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.