Chapter 10 of JavaScript Advanced Programming Reading Sharing - Functions

JavaScript Advanced Programming (4th Edition) Reading Sharing Note Recording

Applicable to comrades who are just getting started

define function

There are two ways to define a function: function declaration and function expression
        Generally speaking, there is no difference between these two methods. In fact, the JavaScript engine treats them differently when loading data. Before any code is executed, the JavaScript engine reads the function declaration and generates the function definition in the execution context . A function expression, on the other hand, must wait until the code executes to its line before generating a function definition in the execution context .

function declaration

chestnut:

function sum (num1, num2) { 
 return num1 + num2; 
}

 function promotion

chestnut:

console.log(sum(10, 10)); //20
function sum(num1, num2) { 
 return num1 + num2; 
}
        The above code works fine because the function declaration is read and added to the execution context before any code is executed (function declaration hoisting).
Execution principle:
        When executing code, the JavaScript engine will first perform a scan and promote the found function declarations to the top of the source code tree. So even if function definitions appear after the code that calls them, the engine will hoist function declarations to the top
Note: If the function declaration in the previous code is changed to an equivalent function expression, an error will occur during execution.
chestnut:
// 会出错
console.log(sum(10, 10)); // // Error! function doesn't exist yet
let sum = function(num1, num2) { 
 return num1 + num2; 
};

function expression

        A function expression looks like a normal variable definition and assignment, i.e. create a function and assign it to a variable.
Functions created in this way are called anonymous functions ( anonymous function ), because there is no identifier after the function keyword

chestnut:

let functionName = function(arg0, arg1, arg2) { 
 // 函数体 
};
// or
let functionName;
functionName = function(arg0, arg1, arg2) { 
 // 函数体 
};

arrow function

ECMAScript 6 added the ability to define function expressions using fat arrow ( => ) syntax.
        For the most part, function objects instantiated by arrow functions behave the same as function objects created by formal function expressions. Anywhere you can use a function expression, you can use an arrow function
chestnut:
let arrowSum = (a, b) => { 
 return a + b; 
};
console.log(arrowSum(5, 8)); // 13
        If there is only one parameter, it can also be without parentheses. Parentheses are only required if there are no parameters, or if there are multiple parameters.
Notice:
        Although the syntax of the arrow function is concise, there are many occasions where it is not applicable. Arrow functions cannot use arguments , super and
new.target , also cannot be used as a constructor. Also, arrow functions don't have a prototype property.

understand parameters

Reading function parameters can use named parameters and arguments object.

     The arguments object is an array-like object, so its elements can be accessed using the bracket syntax (the first argument is arguments[0] ). Instead, to determine how many arguments were passed in, access the arguments.length property.

chestnut:
function sayHi(name, message) { 
 console.log("Hello " + name + ", " + message); 
    console.log(arguments.length);
}

//等价于

function sayHi() { 
 console.log("Hello " + arguments[0] + ", " + arguments[1]); 
    console.log(arguments.length);
}


sayHi('Tom','welcome To My CSDN'); // 2

Another important aspect to understand is that the arguments object can be used with named parameters.
chestnut:
function doAdd(num1, num2) { 
 if (arguments.length === 1) { 
 console.log(num1 + 10); 
 } else if (arguments.length === 2) { 
 console.log(arguments[0] + num2); 
 } 
}

arguments

        The arguments object actually has a callee attribute , which is a pointer to the function where the arguments object is located .
Use arguments.callee to decouple function logic from function name
Use chestnuts:
function factorial(num) { 
 if (num <= 1) { 
 return 1; 
 } else { 
 return num * factorial(num - 1); 
 } 
}

//等价于
function factorial(num) { 
 if (num <= 1) { 
 return 1; 
 } else { 
 return num * arguments.callee(num - 1); //arguments.callee代表factorial
 } 
}

Arguments in arrow functions

        Arrow functions are mentioned above, if the function is defined using the arrow syntax, then the parameters passed to the function will not be accessed using the arguments keyword , but only through the defined named parameters.

Default parameter value

ECMAScript 6 supports explicitly defining default parameters.

chestnut:

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

//箭头函数也可

let makeKing = (name = 'Henry') => `King ${name}`; 
console.log(makeKing()); // King Henry

Extended parameters

In ECMAScript 6 , parameter expansion can be achieved extremely concisely through the spread operator .
   Because the length of the array is known, when using the extension operator to pass parameters, it does not prevent other values ​​from being passed before or after it, including using the extension operator to pass other parameters (normal parameter passing can be combined with extended parameter passing use)
chestnut:
let values = [1, 2, 3, 4]; 
function getSum() { 
 let sum = 0; 
 for (let i = 0; i < arguments.length; ++i) { 
 sum += arguments[i]; 
 } 
 return sum; 
}

console.log(getSum(...values)); // 10

//等价于  getSum(1,2,3,4)

console.log(getSum(-1, ...values)); // 9 
//等价于  getSum(-1,1,2,3,4)
console.log(getSum(...values, 5)); // 15 
console.log(getSum(-1, ...values, 5)); // 14 
console.log(getSum(...values, ...[5,6,7])); // 28
//等价于  getSum(1,2,3,4,5,6,7)

   inside the function

this

  •  this , which behaves differently in standard functions and arrow functions. ( emphasis )
  •  In standard functions, this refers to the context object that uses the function as a method call . At this time, it is usually called this value (when calling a function in the global context of a web page, this points to windows) (whoever calls this function, this points to who).
  •  Which object this this refers to must be determined when the function is called
chestnut:
window.color = 'red'; 
let o = { 
 color: 'blue' 
}; 
function sayColor() { 
 console.log(this.color); 
} 
sayColor(); // 'red' 
o.sayColor = sayColor; 
o.sayColor(); // 'blue'
  • In an arrow function, this refers to the context in which the arrow function is defined. (Where the arrow function is defined, this points to whom)

chestnut:

This refers to the window object, because this arrow function is defined in the window context.
window.color = 'red'; 
let o = { 
 color: 'blue' 
}; 
let sayColor = () => console.log(this.color); 
sayColor(); // 'red' 
o.sayColor = sayColor; 
o.sayColor(); // 'red'

caller

ECMAScript 5 also adds an attribute to function objects: caller. This property refers to the function that called the current function
chestnut:
function outer() { 
 inner(); 
} 
function inner() { 
 console.log(inner.caller); 
} 
outer();
//前面有说过 arguments.callee 是指向arguments所在的函数,所以可以改为
function outer() { 
 inner(); 
} 
function inner() { 
 console.log(arguments.calle.caller); 
} 
outer();

Print result:

 Function properties and methods

Attributes

        As mentioned earlier, functions in ECMAScript are objects and thus have properties and methods. Each function has two properties: length and prototype .
        The length attribute holds the number of named parameters defined by the function
chestnut:
function sayName(name) { 
 console.log(name); 
} 
function sum(num1, num2) { 
 return num1 + num2; 
} 
function sayHi() { 
 console.log("hi"); 
} 
console.log(sayName.length); // 1 
console.log(sum.length); // 2 
console.log(sayHi.length); // 0

method

  • Functions also have two methods: apply() and call() .
  • These two methods will call the function with the specified this value, that is, the value of the this object in the function body will be set when the function is called.
  • The real power of apply() and call() is not to pass parameters to the function, but to control the function call context, that is, this in the function body
    ability to value.
The apply() method receives two parameters: the value of this inside the function and an array of parameters
chestnut:
window.color = 'red'; 
let o = { 
 color: 'blue' 
}; 
function sayColor(a,b,c) { 
 console.log(this.color,a,b,c); 
} 
sayColor(1,2,3); // red,1,2,3
sayColor.apply(this,[2,3,4]); // red,2,3,4
sayColor.apply(window,[2,3,4]); // red ,2,3,4
sayColor.apply(o,[2,3,4]); // blue,2,3,4

call() method: the value of this in the first parameter function , and the remaining parameters to be passed to the called function are passed one by one.

chestnut:

window.color = 'red'; 
let o = { 
 color: 'blue' 
}; 
function sayColor(a,b,c) { 
 console.log(this.color,a,b,c); 
} 
sayColor(1,2,3); // red,1,2,3
sayColor.call(this,2,3,4); // red,2,3,4
sayColor.call(window,2,3,4); // red ,2,3,4
//而在使用 sayColor.call(o)把函数的执行上下文即 this 切换为对象 o 之后,结果就变成了示"blue"了。
sayColor.call(o,2,3,4)// bule,2,3,4

Summarize:

1. Difference

  • The parameters passed by the call are the sequence 1, 2, 3
  • The parameters passed by apply are set type [1, 2, 3]

2. Similarities

  • call and apply are to replace the this pointer inside the previous function and pass parameters.
  • Function: Can automatically execute the previous function
  • Both have two parameters: a. the object to replace b. the passed value

bind()

        ECMAScript 5 defines a new method for the same purpose: bind() . The bind() method creates a new function instance whose this value is bound to the object passed to bind() .
chestnut:
window.color = 'red'; 
var o = { 
 color: 'blue' 
}; 
function sayColor() { 
 console.log(this.color); 
} 
let objectSayColor = sayColor.bind(o); 
objectSayColor(); // blue

Guess you like

Origin blog.csdn.net/weixin_42307283/article/details/129382837