1. Function description

1.1 Functions are first-class objects

  • Because they can have properties and methods just like any other object.
  • They differ from other objects in that functions can be called.
  • Each Function is actually a Function object

1.2 the return value

  • Default return undefined
  • Use a return statement to specify a value to return (except by calling a constructor using the new keyword)

1.3 Function Parameters

  • When a function is called, the values passed to the function are called arguments to the function (value passing),
  • The function arguments at the corresponding positions are called parameters.
  • If the argument is a variable that contains the original value (number, string, Boolean), the value of the argument does not change even if the function internally changes the value of the corresponding parameter.
  • If the argument is an object reference, the corresponding argument refers to the same object as the argument. If the function internally changes the value of the corresponding parameter, the value of the object to which the argument points changes when it returns.

1.4 this point

  • When a function executes, the this keyword does not refer to the running function itself, but to the object calling the function
  • If you want to get a reference to the function itself inside a function, use either the function name or the arguments.callee property (not available in strict mode), or the latter if the function is an anonymous function.

2. Function definition

2.1 Function Declaration

2.1.1 usage

Function name([parameter, parameter,... parameter) {statements}Copy the code
function myFunc(theObject) {
  theObject.make = "Toyota";
}

var mycar = {make: "Honda".model: "Accord".year: 1998};
var x, y;

x = mycar.make;     // x gets the value "Honda"

myFunc(mycar);
y = mycar.make;     // y gets the value "Toyota"
                    // (make property changed by function)

Copy the code

2.1.2 Function declaration enhancement

  • Function declarations in JavaScript are promoted to function definitions, which can be used before function declarations.
  • The function declaration also creates a variable with the same name as the function. Therefore, functions defined by function declarations can be accessed by function names in the scope in which they are defined
hoisted(); // "foo"

function hoisted() {
     console.log("foo");
}

/* equal to*/
var hoisted; 

hoisted = function() {
  console.log("foo");
}
hoisted();
// "foo" 

Copy the code

2.2 Function Expression

2.2.1 usage

Let variable name = function function name (parameter, parameter,... Parameter) {statements};Copy the code
  • The function name may be omitted; in this case the function is anonymous.
  • A function name is just a local variable in the function body.
const square = function(number) { return number * number; };
var x = square(4); // x gets the value 16

const factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)};
console.log(factorial(3));

Copy the code

2.2.2 No promotion

 notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function() {
   console.log('bar');
};
Copy the code

2.3 Function Generator Declaration (function* declaration)

Define a generator function that returns a generator object.

Function * Function name (parameter, parameter... Parameter) {statements}Copy the code
function* generator(i) {
  yield i;
  yield i + 10;
}

const gen = generator(10);

console.log(gen.next().value);
// expected output: 10

console.log(gen.next().value);
// expected output: 20
Copy the code
  • Generator functions can pause during execution and then resume execution from the pause.
  • Calling a generator function does not immediately execute its statements, but returns an iterator of the generator.
  • When the iterator’s next() method is called for the first time (subsequent), the statements inside it are executed until the first yield occurs, immediately following the value the iterator returns.
  • Or if yield* (with an asterisk) is used, the execution is handed over to another generator function (the generator is currently suspended).
  • The next() method returns an object containing two properties: value and done,
  • The value property represents the return value of this yield expression,
  • The done attribute is Boolean and indicates whether the generator has any subsequent yield statements, that is, whether the generator function has finished executing and returned.

2.4 Function generator Expressions (Function * expressions)

  • Function * expressions and function* declarations are similar and have nearly the same syntax.
  • The main difference between function* expressions and function* declarations is the function name,
  • That is, when creating anonymous functions, function* expressions can omit the function name
var x = function* (y) {
   yield y * y;
};
Copy the code

2.5 Arrow Function Expression (=>)

(param1, param2,... , paramN) => { statements }Copy the code
  • Shorter function
  • This is not binding

2.5.1 Shorter functions

var elements = [
  'Hydrogen'.'Helium'.'Lithium'.'Beryllium'
];

elements.map(function(element) {
  return element.length;
}); // Return array: [8, 6, 7, 9]

// The normal function above can be rewritten as the arrow function below
elements.map((element) = > {
  return element.length;
}); // [8, 6, 7, 9]

// If the arrow function has only one argument, omit the parentheses for the argument
elements.map(element= > {
 return element.length;
}); // [8, 6, 7, 9]

// When the body of an arrow function has only one 'return' statement, you can omit the 'return' keyword and the curly braces of the method body
elements.map(element= > element.length); // [8, 6, 7, 9]

// In this case, since we only need the 'length' attribute, we can use parameter deconstruction
// Note that string 'length' is the name of the attribute we want to obtain, while 'lengthFooBArX' is just a variable name,
// Can be replaced with any valid variable name
elements.map(({ "length": lengthFooBArX }) = > lengthFooBArX); // [8, 6, 7, 9]

Copy the code

2.5.2 Not Binding this

function Person() {
  // The Person() constructor defines' this' as its own instance.
  this.age = 0;

  setInterval(function growUp() {
    // In non-strict mode, growUp() defines' this' as a global object,
    // Not the same as' this' defined in the Person() constructor.
    this.age++;
  }, 1000);
}

var p = new Person();


Copy the code
<! - bythisValues assigned to closed variables can be resolvedthisProblem - >function Person() {
  var that = this;
  that.age = 0;

  setInterval(function growUp() {
    // The callback refers to the 'that' variable, whose value is the expected object.
    that.age++;
  }, 1000);
}
Copy the code
<! Arrow functions will not create their ownthisIt inherits only from the upper layer of its scope chainthis-->
function Person(){
  this.age = 0;

  setInterval(() = > {
    this.age++; / / | this | to p instance correctly
  }, 1000);
}

var p = new Person();
Copy the code

2.6 Function constructor expressions (Is not recommended)

// If the result is true, all functions are Function objects
(function(){}).constructor === Function //true
Copy the code

2.6.1 description

  • Function objects generated using the Function constructor are parsed at Function creation time.
  • It’s much less efficient than if you use function declarations or function expressions and call them in your code,
  • Because functions created using the latter are parsed along with the rest of the code.
  • Calling the constructor of a Function as a Function (instead of using the new keyword) is the same as calling it as a constructor.
<! -- Can be executed correctly -->const sum = new Function("a"."b"."return a + b");
console.log(sum(2.6)); <! -- Can be executed correctly -->const sum2 = Function.prototype.constructor( "a"."b"."return a + b" );
console.log(sum2(2.6));
Copy the code
<! New Function (parameter, parameter,... Const sum = new Function('a', 'b', 'return a + b'); const sum = new Function('a', 'b', 'return a + b'); console.log(sum(2, 6)); // expected output: 8Copy the code

2.6.2 Instance Properties

  • Function. Caller gets the object that calls the Function. (Compatibility issues exist)
  • Function.length Gets the number of received arguments to the Function.
  • Function.name Gets the name of the Function.

2.6.3 Instance methods

  • Function.prototype.apply() applies methods to one object in the context of another; Arguments can be passed in as arrays.
  • Function.prototype.bind()
    • The bind() method creates a new function, called the bind function.
    • When called, the binding function takes as this the first argument passed to the bind() method when it was created,
    • The second and subsequent arguments passed to the bind() method are called as arguments to the original function, along with arguments from the bind function’s runtime itself, in that order.
  • Function.prototype.call() applies methods to one object in the context of another; Parameters can be passed in as a list.
  • Function. The prototype. The toString () Function for realizing the source string. Cover the Object. The prototype. The toString method.

2.6.4 Different from function declarations and function expressions

  • Like function expressions, there is no function declaration promotion. Cannot be called before declaration
  • Cannot create a current environment closure, can only be created in the global environment
  • You can access only global variables and your own local variables
    const x = 10;
    function createFunction1() {
        const x = 20;
        return new Function("return x;"); // the x here refers to x in the uppermost global scope
    }
    function createFunction2() {
        const x = 20;
        function f() {
            return x; // the x here points up to x in the local scope
        }
        return f;
    }
    const f1 = createFunction1();
    console.log(f1()); / / 10
    const f2 = createFunction2();
    console.log(f2()); / / 20
Copy the code

2.6.5 Reasons for avoiding use

  • The Function body string passed to the Function constructor is parsed each time the constructor is called.

  • Although Function expressions create a closure each time, the Function body is not parsed repeatedly, so Function expressions are still faster than “new Function(…) “. “

  • In functions generated by parsing the Function constructor string, the embedded Function expressions and Function declarations are not parsed repeatedly.

2.7 Constructor of generator function (Is not recommended)

  • The GeneratorFunction constructor generates a new GeneratorFunction object.
  • In JavaScript, generator functions are actually instance objects of GeneratorFunction.
  • GeneratorFunction is not a global object. It can be obtained by the following code.
Object.getPrototypeOf(function* (){}).constructor
Copy the code

2.7.1 grammar

New GeneratorFunction ([arg1[, arg2[,...argN]],] functionBody string)Copy the code
var GeneratorFunction = Object.getPrototypeOf(function* (){}).constructor
var g = new GeneratorFunction("a"."yield a * 2");
var iterator = g(10);
console.log(iterator.next().value); / / 20

Copy the code

2.7.2 Reasons for avoiding use

  • When a function is created, the GeneratorFunction object created by the GeneratorFunction constructor is parsed.
  • This is less efficient than declaring generator functions using function* expressions,
  • Generator functions created using the GeneratorFunction constructor do not create closures for their creation context; They are always created globally.
  • When running them, they can only access their own local and global variables, not the variables of the scope called from the GeneratorFunction constructor.

3. Function scope

  • Variables defined within a function cannot be accessed anywhere outside the function, because variables are defined only inside the domain of that function.
  • A function can access any variable or function in the scope in which it is defined. For example, a function defined in the global domain can access all variables defined in the global domain.
  • A function defined in another function can also access all variables defined in its parent function and any other variables that the parent function has access to.
// The following variables are defined in the global scope
var num1 = 20,
    num2 = 3,
    name = "Chamahk";

// This function is defined in global scope
function multiply() {
  return num1 * num2;
}

multiply(); / / return to 60

// An example of nested functions
function getScore() {
  var num1 = 2,
      num2 = 3;

  function add() {
    return name + " scored " + (num1 + num2);
  }

  return add();
}

getScore(); // return "Chamahk map 5"

Copy the code

4, closures

  • JavaScript allows functions to be nested,
  • An inner function can access all variables and functions defined in the outer function, as well as all variables and functions accessible by the outer function.
  • External functions cannot access variables and functions defined in internal functions. This provides some security for the variables of the inner function.
  • Since the inner function has access to the scope of the outer function, when the inner function has a lifetime larger than the outer function, the lifetime of the variables and functions defined in the outer function will take longer to execute than the inner function.
  • A closure is created when an inner function is accessed in a certain way by any of the outer function scopes.
var pet = function(name) {          // The external function defines a variable "name"
  var getName = function() {
    // The inner function can access the "name" defined by the outer function
    return name;
  }
  // Returns the inner function, thus exposing it to the outer function scope
  return getName;
};
myPet = pet("Vivie");

myPet();    
Copy the code

4.1 Naming Conflict

  • Naming conflicts occur when two parameters or variables in the same closure scope have the same name.
  • The nearest scope has higher priority, so the nearest one has the highest priority and the farthest one has the lowest priority. This is the scope chain.
  • The first element of the chain is the innermost scope, and the last element is the outermost scope.
function outside() {
  var x = 5;
  function inside(x) {
    return x * 2;
  }
  return inside;
}

outside()(10); // returns 20 instead of 10
Copy the code

5. The arguments object

  • Arguments is an array-like object corresponding to the arguments passed to the function
  • The arguments variable is just an “array object”, not an array.
  • To call it an array-like object means that it has an index number and a length attribute.
  • However, it does not own all of the Array object manipulation methods.
  • Arguments objects are local variables available in all (non-arrow) functions.
function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1.2.3);
Copy the code

5.1 attributes

  • Arguments. callee: Function currently being executed.
  • Arguments. caller: Calls the function that currently executes the function.
  • Arguments. length: The number of arguments passed to the function.

6. Function parameters

Starting with ECMAScript 6, there are two new types of parameters: default parameters and residual parameters

6.1 Default Parameters

In JavaScript, the default value of a function parameter is undefined. In the past, the common strategy for setting default parameters was to test for undefined in the body of a function and give the parameter a default value if so.

function multiply(a, b) {
  b = (typeofb ! = ='undefined')? b :1;

  return a*b;
}

multiply(5); / / 5

Copy the code
<! -- Use default arguments, check in function body is not needed -->function multiply(a, b = 1) {
  return a*b;
}

multiply(5); / / 5
Copy the code

6.2 Remaining Parameters

The residual argument syntax allows an indefinite number of arguments to be represented as arrays.

function multiply(multiplier, ... theArgs) {
  return theArgs.map(x= > multiplier * x);
}

var arr = multiply(2.1.2.3);
console.log(arr); / / (2, 4, 6]
Copy the code

Refer to the link

  • Function
  • Functional expression
  • function*
  • Arrow function
  • The remaining parameters
  • GeneratorFunction