[JavaScript Grammar Learning] full introduction to Functions

Source: Internet
Author: User
Tags function definition variable scope

Function

ES6 syntax supports rest parameters

The rest parameter can only be defined at the end of the parameter, using ... Identity. The rest parameter receives an empty array if the passed parameters are not filled with the normal defined parameters.

Variable scope

Variables declared with Var are actually scoped, and intrinsic functions can access variables defined by external functions, looking for variables starting from their own function definitions and looking inside out. If an intrinsic function defines a variable with the same name as an external function, the variables of the intrinsic function will mask the variables of the outer function.

Variable Promotion

The JS function will first scan the entire function body statement to promote all declared variables to the top of the function. It is therefore recommended that you strictly abide by the "Declare all variables inside function" rule when defining variables inside a function.

Global scope

Variables that are not defined within any function have global scope, and the Default Global object window

namespace namespaces

Bind all variables and functions in a global variable

Local scope

ES5 does not have a block-level scope, so the Let keyword is introduced in ES6. Use let instead of Var to declare a block-level scope variable

Constant

The Const keyword was introduced in ES6 to define constants, and both const and let have block-level scopes

This

In a separate function scope, if this does not specify an object. So in strict mode this points to undefined, in non-strict mode this points to window

What if you change the point of this?

1. The Apply method can specify the this point of the function, receive two parameters, the first is the variable that this needs to bind, and the second represents an array of arguments for the function itself

2. The call method packages the parameters in sequence into an array for incoming

The invocation of a normal function is usually to bind this to null

var count = 0; var oldparseint =function() {    count+=1;     return oldparseint.apply (null, arguments);};

Closed Package

functions defined inside a function can access the properties of local variables of external functions called closures

Classic pit: return function do not reference any loop variables or variables that will change later

functioncount () {varArr=[];  for(varI=1; i<=3; i++) {Arr.push (function(){            returni*i;    }); }    returnarr;}varResults =count ();varf1= results[0];varF2= results[1];varf3= results[2];f1 (); F2 (); F3 ();//The return values of these three functions are all

ES6 the extension of the function to 1. Default values for function parameters

ES6 can specify a default value for the function's arguments, avoiding the use of the | | The syntax to implement the default value

However, there is a flaw, or the Boolean value of the first argument of a statement's logical expression will also use the default value if it is false. such as passing in an empty string, converting to a Boolean value is False

Therefore, it is generally necessary to first determine whether the variable has a value

// ES5 Syntax function log (x, y) {    if(typeof y = = ' undefined ')        {= ' world ';    }} function log (x, y) {    if(arguments.length = = 1)        {= ' world ';    }}

In ES6, the default value is assigned directly after the parameter definition using the equals sign

function log (x, y = "World") {    console.log (x, y);} Log ("Hello");  // Hello World log ("Hello", "es6");  // Hello es6 log ("Hello", "");  // Hello

Parameter variables are declared by default, so the let or const declarations cannot be used again in the body of the function.

Small pits:

If the function argument is an object, but does not give the entire object a default value. If you do not pass in a parameter when calling the function, you will get an error.

Be alert to the following situations at the last moment

function m1 ({x = 0, y = 0} = {}) {    return  [x, y];} function m2 ({x, y} = {x:0, y:0}) {    return  [x, y];}

The position of the parameter default value must be the last function parameter, and if it is not the last argument, the parameter with the default value needs to be displayed in order to skip the parameter, and null cannot be skipped. undefined This can refer to the object's deconstruction assignment

2. Length property of the function

The length property of the function = the number of arguments to the function-Specifies the number of parameters for the default value

The rest parameter is also not counted in the length property

3. Scope

If the parameter default value is a variable, the variable is in the same scope as the scope rules of the other variables. First, the current function scope, and then the global scope.

If the default value variable is not already generated inside the function when the function is called, the variable points to the global scope.

If the default value of a function call is a function, then the scope of the function is the scope at which it is declared, that is, the global scope.

4. Rest Parameters

ES6 introduces the rest parameter, the rest parameter must be the last parameter, that is, after the normal parameter and the default value parameter.

The rest parameter can replace the arguments variable

Const Sortnumbers = () =

The rest parameter variable represents an array, so array methods can be used on this variable.

function push (array, ... items)    {Items.foreach (item) = {        Array.push (item);    }); var arr =1, 2, 3, 4);

5. Spread extension operator

You can convert an array to a comma-delimited sequence of arguments, using:

1. Apply method to replace array

2. Merging arrays

3. Combining with analytic assignment

4. function return value resolution

5. String parsing

6. Parsing of Class array objects

6. The Name property of the function

ES6 only writes the name attribute into the standard, but many browsers have implemented this feature

In addition, ES6 specifies that the anonymous function also has a name attribute, and returns the actual function name. In most browsers, the empty string is still returned.

Function constructor returns an instance of the functions, Name property = ' Anonymous '

After the function has this binding through the bind () method, the Name property of the returned function adds a "bound" prefix to the original Name property value

7. Arrow function (emphasis in the focus)

1. If the function does not require parameters or requires more than one parameter, use () to enclose the parameter part. Only functions that have one parameter can be omitted ()

2. If the function body has more than one statement, you need to enclose the function body with {}. and return using the return statement. You can omit {} for a statement

3. If the function returns an object, it needs to be nested outside of {} ()

4. The This object in the function body has changed to represent the object where the function definition is located. Instead of the original object where it was used.

5. The arrow function cannot be used as a constructor function

6. Arguments objects cannot be used in arrow functions

7. The yield statement cannot be used in an arrow function

8. The arrow function essentially does not have this, at the same time arguments, Super, New.target also does not exist

[JavaScript Grammar Learning] full introduction to Functions

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.