Technology Sharing

JavaScript Advanced Programming (Fourth Edition) - Learning Record Function (Part 1)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

function

Each function is an instance of the Function type, and Function has properties and methods, just like other reference types. Functions are objects, and the function name is a pointer to the function object, and is not necessarily tightly bound to the function itself.

Function definition: function declarative definition

  1. function sum (n1,n2){
  2. return n1+n2;
  3. }

Function definition function expression

  1. let sum = function(n1,n2){
  2. return n1+n2;
  3. };

Function definition arrow function

  1. let sum = (n1,n2)=>{
  2. return n1+n2;
  3. };

Function definition constructor

  1. let sum = new Function("n1","n2","return n1+n2");
  2. /*这个构造函数接收任意多个字符串参数,
  3. 最后一个参数始终会被当成函数体,
  4. 而之前的参数都是新函数的参数*/

Arrow Functions

Anywhere you can use a function expression, you can use an arrow function.

  1. let sum = (a,b)=>{
  2. return a+b;
  3. };
  4. let sum1 = function(a,b){
  5. return a+b;
  6. };
  7. //箭头函数适合嵌入函数的场景
  8. let arr = [1,2,3];
  9. console.log(arr.map(function(i) {return i+1;}));
  10. console.log(arr.map((i)=>{return i+1;}));
  11. //二者结果一样,但是箭头函数更为简洁
  12. //如果只有一个参数,括号可以不用。只有没有参数,或者多个参数的情况下,才使用括号
  13. let double = (x)=>{return 2*x;};
  14. let triple = x => {return 3*x};
  15. //箭头函数也可以不使用大括号,但这样会改变函数的行为。使用大括号就说明包含函数体,可以在一
  16. //个函数中包含多条语句,跟常规函数一样。如果不使用,后面只能有一行代码。
  17. let double = (x)=>{return 2*x;};
  18. let triple = x=>3*x;

Although arrow functions have concise syntax, they are not applicable in many situations. Arrow functions cannot use arguments, super, new.target, and cannot be used as constructors. In addition, arrow functions do not have a prototype property.

Parameters in Arrow Functions

If the function is defined using arrow syntax, the arguments passed to the function cannot be accessed using the arguments keyword, but only through the defined named parameters.

  1. function foo() {
  2. console.log(arguments[0]);
  3. }
  4. foo(5); // 5
  5. let bar = () => {
  6. console.log(arguments[0]);
  7. };
  8. bar(5); // ReferenceError: arguments is not defined

Function name

A function can have multiple names.

  1. function sum(num1, num2) {
  2. return num1 + num2;
  3. }
  4. console.log(sum(10, 10)); // 20
  5. let anotherSum = sum;
  6. console.log(anotherSum(10, 10)); // 20
  7. sum = null;
  8. console.log(anotherSum(10, 10)); // 20

Default parameter values

You can assign a default value to a parameter by using = after the parameter in the function definition.

  1. function makeKing(name = 'Henry') {
  2. return `King ${name} VIII`;
  3. }
  4. console.log(makeKing('Louis')); // 'King Louis VIII'
  5. console.log(makeKing()); // 'King Henry VIII'

Default parameter values ​​are not limited to primitive values ​​or object types. You can also use the value returned by the calling function.

  1. let romanNumerals = ['I', 'II', 'III', 'IV', 'V', 'VI'];
  2. let ordinality = 0;
  3. function getNumerals() {
  4. // 每次调用后递增
  5. return romanNumerals[ordinality++];
  6. }
  7. function makeKing(name = 'Henry', numerals = getNumerals()) {
  8. return `King ${name} ${numerals}`;
  9. }
  10. console.log(makeKing()); // 'King Henry I'
  11. console.log(makeKing('Louis', 'XVI')); // 'King Louis XVI'
  12. console.log(makeKing()); // 'King Henry II'
  13. console.log(makeKing()); // 'King Henry III'

Parameter expansion and collection

ES6 adds the spread operator, which can be used to operate and combine collection data very concisely. The most useful scenario for the spread operator is the parameter list in the function definition, where it can make full use of the weak typing and variable parameter length characteristics of this language. The spread operator can be used to pass parameters when calling a function, and can also be used to define function parameters.

Extended Parameters

  1. let values = [1, 2, 3, 4];
  2. function getSum() {
  3. let sum = 0;
  4. for (let i = 0; i < arguments.length; ++i) {
  5. sum += arguments[i];
  6. }
  7. return sum;
  8. }
  9. //不使用扩展操作符实现累加
  10. console.log(getSum.apply(null,values));
  11. //使用扩展操作符
  12. console.log(getSum(...values));

Collecting parameters

If there are named parameters before the collection parameter, only the remaining parameters will be collected; if not, an empty array will be obtained. Because the result of collecting parameters is mutable, it can only be used as the last parameter.

  1. function getProduct(...values,lastValue){}//不可以
  2. function ignoreFirst(firstValue,...values){console.log(values)}//可以
  3. ignoreFirst(); // []
  4. ignoreFirst(1); // []
  5. ignoreFirst(1,2); // [2]
  6. ignoreFirst(1,2,3); // [2, 3]

Function declaration and function expression

Before any code is executed, the JavaScript engine will read the function declaration and generate the function definition in the execution context. However, the function expression must wait until the code is executed to its line before generating the function definition in the execution context.
  1. // 没问题
  2. console.log(sum(10, 10));
  3. function sum(num1, num2) {
  4. return num1 + num2;
  5. }
  6. /*函数声明提升*/
  7. // 会出错
  8. console.log(sum(10, 10));
  9. let sum = function(num1, num2) {
  10. return num1 + num2;
  11. };