function
Introduction to the
What is a function
-
What is a function? Functions are designed to encapsulate code. A function is a block of code that can be executed repeatedly at any time
-
Function format
function/* Function name */(/* Parameter list */){ /* Encapsulated code */; } Copy the code
-
Disadvantages of not using functions
- Too much redundant code
- Requirements change and a lot of code needs to be modified
-
The benefits of using functions
- There’s less redundant code
- Requirements change and there is less code to modify
The defining steps of a function
- A fixed format for writing functions
- Give the function a meaningful name
- To improve the readability of the code
- Function names are also a type of identifier, so you need to follow the naming conventions and conventions for identifiers
- Determine the parameter list of the function to see if any auxiliary data needs to be passed in to use the function
- Copy the code to be wrapped into {}
- The return value of a function can be determined by the return data; Returns the result of a calculation in a function to the caller of the function
Notice of the function
-
A function may have either tangible or no parameters (zero or more). When we define a function, the variables in the function () are called parameters
// Function with no parameters function say() { console.log("hello world"); } say(); // hello world Copy the code
// A function of a corporeal parameter function say(name) { console.log("hello " + name); } say("fhs"); // hello fhs Copy the code
-
A function may or may not have a return value
// A function with no return value function say() { console.log("hello world"); } say(); Copy the code
// A function that returns a value function getSum(a, b) { return a + b; } let res = getSum(10 , 20); console.log(res); / / 30 Copy the code
-
The function does not explicitly return a value via return, but returns undefined by default
function say() { console.log("hello world"); return; } let res = say(); console.log(res); // undefined Copy the code
-
A return function is similar to a break, so you cannot write a statement after a return (it will never be executed)
function say() { console.log("hello world"); return; console.log("Code after return"); } say(); // hello world Copy the code
-
The number of arguments and the number of parameters can be different when you call a function and the data passed in when you call a function is called an argument
-
Functions in JavaScript, like arrays, refer to data types (object types) and since a function is a data type, it can also be stored in a variable that you can use to find the function and execute it in the future
let say = function () { console.log("hello world"); } say(); // hello world Copy the code
Functions and parameters
Parameters of the arguments
-
Because the console. The log (); Is also called by (), so log is also a function
-
The log function can take one or more arguments
-
Why can the log function take 1 or more arguments
-
Arguments hold all arguments passed to the function
-
Each function has a thing called Arguments, which is actually a pseudo-array
function getSum() { let sum = 0; for (let i = 0; i < arguments.length; i++){ let num = arguments[i]; sum += num; } return sum; } let res = getSum(10.20.30.40); console.log(res); / / 100 Copy the code
Each argument inside the function parentheses is put into the arguments object (pseudoarray)
/ / added function test(a) { console.log(arguments); } test(0.1.2.3.4.5); // [Arguments] { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5 } Copy the code
Extended operator
-
Let [a…b] = [1, 3, 5]; let [a…b] = [1, 3, 5]; a = 1; b = [3, 5];
-
The extension operator, to the right of the equals sign, unwinds the data in the array
let arr1 = [1.3.5]; let arr2 = [2.4.6]; let arr = [...arr1, ...arr2]; let arr = [1.3.5.2.4.6]; Copy the code
-
The extension operator’s role in the parameter list of a function packs up all the extra arguments passed to the function into an array. Note: As on the left side of the equal sign, only the arguments can be written at the end of the parameter list
function getSum (a, ... values) { console.log(a); console.log(values); } getSum(10.20 , 30); / / 10 / / 20, 30 Copy the code
Default value of function parameters
Logical operators to give before ES6 parameter to specify the default format: condition A | B | conditions
- If condition A is true, then condition A is returned
- If condition A is not true, condition B is returned regardless of whether condition B is true
function getSum(a, b) {
a = a || "211";
b = b || "996";
console.log(a, b);
}
getSum(123."abc"); // 123, "ABC" (" ABC ")
Copy the code
Starting with ES6, you can specify the default value directly after the parameter with = (which corresponds to the specified default value of the deconstructed assignment). Note: Default values starting with ES6 can also be obtained from other functions
function getSum(a = "211", b = getDefault()) {
console.log(a, b);
}
getSum();
function getDefault() {
return "996"
}
Copy the code
Function as the return value
- Assign functions to other variables
let say = function () {
console.log("hello world");
}
let fn = say;
fn();
Copy the code
- Take a function as an argument to another function
let say = function () {
console.log("hello world");
}
function test(fn) { // let fn = say;
fn();
}
test(say);
Copy the code
- Function as the return value of another function
function test() {
// Note: functions cannot be nested in other programming languages, but functions can be nested in JavaScript
let say = function () {
console.log("hello world");
}
return say;
}
let fn = test(); // let fn = say;
fn();
Copy the code
Note: Functions cannot be nested in other programming languages, but they can be nested in JavaScript
Fancy function
Anonymous functions
- What are anonymous functions? An anonymous function is a function without a name
- Anonymous functions cannot be defined without use
- Application scenarios of anonymous functions
- As arguments to other functions
- As a return value for other functions
- As a function that executes immediately
- A named function
function say() {
console.log("hello fhs");
}
let say = function() {
console.log("hello fhs");
}
Copy the code
- Anonymous functions
function() {
console.log("hello fhs");
}
Copy the code
- Anonymous functions as arguments to other functions
function test(fn) { // let fn = say;
fn();
}
test(function () {
console.log("hello world");
});
Copy the code
- Anonymous functions as return values for other functions
function test() {
return function () {
console.log("hello fhs");
};
}
let fn = test(); // let fn = say;
fn();
Copy the code
- Anonymous function as an immediate function Note: If you want an anonymous function to execute immediately, you must wrap the function definition with ()
(function () {
console.log("hello it666"); }) ();Copy the code
Arrow function
-
What is an arrow function?
-
Arrow functions are a new format for defining functions in ES6
-
Purpose: To simplify the code used to define functions, and to give a set of fancy uses of this
-
let arr = new Array(a);let arr = []; Copy the code
-
-
How were functions defined before ES6
functionFunction name (The parameter list){ /* Code that needs to be wrapped */; } letFunction name =function(The parameter list){ /* Code that needs to be wrapped */; } Copy the code
-
New function definition method in ES6
letFunction name =(The parameter list) = >{ /* Code that needs to be wrapped */; } Copy the code
-
Points to note in arrow function:
-
If there is only one parameter in the arrow function, () can be omitted
// function say() { // console.log("hello lnj"); // } let say = () = > { console.log("hello lnj"); } say(); Copy the code
-
If {} has only one line of code in the arrow function, {} can also be omitted
// function say(name) { // console.log("hello " + name); // } // let say = (name) => { // console.log("hello " + name); // } // let say = name => { // console.log("hello " + name); // } let say = name= > console.log("hello " + name); // All the bells and whistles say("ccc"); Copy the code
-
If the body of an arrow function contains only one return statement, you can omit the return keyword and the curly braces of the method body
var elements = [ 'Hydrogen'.'Helium'.'Lithium'.'Beryllium' ]; elements.map(element= > element.length); // [8, 6, 7, 9] Copy the code
-
If the body of the arrow function has only one line of code that returns an object, it can be written like this:
// Enclose the object to be returned with parentheses let getTempItem = id= > ({ id: id, name: "Temp" }); // Do not write like this. // Object braces are interpreted as function body braces let getTempItem = id= > { id: id, name: "Temp" }; Copy the code
-
The arrow function is different from the this of the orthodox function
-
This in the arrow function is the parent scope of this, not the caller
-
The arrow function’s this cannot be changed
-
The object will not be this of the arrow function
let p = { name: "fhs".say: function () { console.log(this); }, // Arrow functions are globally scoped because they are not placed in other functions // In JS a new scope is opened only when a new function is defined. hi: () = > { console.log(this); } } p.say(); // {name: "FHS ", say: ƒ} p.hi(); // Window console.log(this); // Window Copy the code
- The function will be this of the arrow function
function Person() { this.name = "fhs"; this.say = function () { console.log(this); } // The arrow function belongs to another function because it belongs to another function (the current other function is the constructor) // Since the arrow function belongs to the constructor, this in the arrow function is the constructor's this this.hi = () = >{ console.log(this); }}let p = new Person(); p.say(); // Person p.hi(); // Person Copy the code
- The arrow function’s this cannot be changed
function Person() { this.name = "fhs"; this.say = function () { console.log(this); } this.hi = () = >{ console.log(this); }}let p = new Person(); p.say.call({name: "zs"}); // {name: "zs"} /* Note: the arrow function this always looks at the scope it belongs to. This cannot be changed by bind/call/apply p.hi.call({name: "zs"}); // Person Copy the code
- Class is different again, grumpy
class Person{ constructor(name){ this.name = name; } say = function () { console.log(this); } hi = () = >{ console.log(this); }}let a = new Person("fhs"); console.log(a.say()); // undefined console.log(a.hi()); // undefined Copy the code
- This is still undefined
class Person{ constructor(name){ this.name = name; this.say = function(){ console.log(this); } this.hi = () = >{ console.log(this); }}}let a = new Person("fhs"); console.log(a.say()); // undefined console.log(a.hi()); // undefined Copy the code
-
-
This is this, scoped chain is scoped chain, scoped chain is not the same thing
Recursive function
- What is a recursive function? recursion
- A recursive function is a function that calls itself within a function, so we call it a recursive function
- Recursive functions can realize the function of loops to a certain extent
- Recursive functionPay attention to the point:
- Each call to a recursive function opens up a new piece of storage, so performance is not very good
- When the function completes, it returns to where the function was called
// let pwd = -1;
// do{
// PWD = prompt(" Please enter password ");
// }while (pwd ! = = "123456");
// alert(" welcome back ");
function login() {
// 1. Receive the password entered by the user
let pwd = prompt("Please enter your password");
// 2. Check whether the password is correct
if(pwd ! = ="123456"){
login();
}
// 3
alert("Welcome back."); // If you enter the password correctly, you will play the same welcome back
}
login();
Copy the code
Scope and scope chain
background
There are two ways to define variables in JavaScript
- Before ES6: var variable name;
- ES6 new: let variable name;
Var is different from let
- Whether you can repeat the definition
- Using var to define variables, you can repeatedly define variables with the same name, and the last one overwrites the first one
- If a variable is defined by let, it cannot be defined “in the same scope” again
- Whether it can be used before definition
- Using var to define variables, you can use them before you define them (pre-parse)
- Variables defined by let cannot be used and then defined (not preparsed)
- Can be scoped by {}
- Both var and let are global variables defined outside {}
- Put the variable defined by var in a separate {}, and also a global variable
- Put the let variable in a separate {}, which is a local variable
Global, local (function), block-level scope
- In JavaScript, the scope outside {} is called a global scope
- In JavaScript, the scope in {} after functions is called “local scope “, or” function scope “.
- In ES6, as long as {} is not combined with functions, it is “block-level scope”. Block-level scope can only constrain lets
- The difference between block-level scope and local scope(Infuriating around)
- Variables defined by var in block-level scope are global variables
- Variables defined by var in a local scope are local variables
- In both block-level and local scopes, omitting a let or var before a variable becomes a global variable (strict mode does not omit it)
- Block-level scopes (neither selection structures nor loop structures are functions)
{
// block-level scope
}
if(false) {// block-level scope
}
switch () {
// block-level scope
}
while (false) {// block-level scope
}
for(;;) {// block-level scope
}
do{
// block-level scope
}while (false);
Copy the code
- Function scope (local scope)
function say() {
// local scope
}
Copy the code
- Analysis of the var
{
// block-level scope
var num = 123; // Global variables
}
console.log(num); / / 123
function test() {
var value = Awesome!; // Local variables
}
test();
console.log(value); / / an error
Copy the code
- Var and let in block-level scope
{
// var num = 678; // Global variables
// let num = 678; // Local variables
num = 678; // Global variables, in strict mode this will report an error, causing comfort
}
console.log(num);
Copy the code
- Var and let in local (function) scope
function test() {
// var num = 123; // Local variables
// let num = 123; // Local variables
num = 123; // Global variables, in strict mode this will report an error, causing comfort
}
test();
console.log(num);
Copy the code
Consider: compared with VAR, the flexibility of LET is greatly weakened, but the ease of use is greatly increased, which is the benefit of rules
Note:
- Variables with the same name can appear in different scopes (yes but not recommended)
- Whenever a let is present, a variable of the same name cannot appear in the same scope, even if the other is a var
The scope chain
A global scope is also called a level 0 scope
Note: Beginners studying “scope chains” are advised to separate ES6 from ES6
Scope chains prior to ES6
- Need to be clear:
- ES6 previously defined variables through var
- ES6 previously had no block-level scopes, only global and local scopes
- Before ES6, all functions outside the braces were global scopes
- Before ES6, local scopes were in the braces of functions
- ES6 pre-scope chain
- The global scope is also called the level 0 scope
- The scope that the definition function opens is level 1/2/3 /… scope
- JavaScript links these scopes together into a chain called the scope chain 0 –> 1 —-> 2 —-> 3 —-> 4
- Except for the level 0 scope, the current scope level is equal to the previous level +1
- The variable looks up rules in the scope chain
- First look at the current, found using the current scope found
- If not found in the current scope, go to the upper scope
- And so on up to level 0. If level 0 scope is not found, an error is reported
// Global scope/level 0 scope
var num = 123;
function demo() {
// Level 1 scope
var num = 456;
function test() {
// Level 2 scope
var num = 789;
console.log(num);
}
test();
}
demo(); / / 789
Copy the code
The chain of scopes from ES6 onwards
- Need to be clear:
- ES6 defines variables through let
- ES6 in addition to global scope, local scope, but also a new block – level scope
- Although block-level scope is added in ES6, variables defined by let in block-level scope are no different from function scope (both are local variables).
- ES6 scope chain
- The global scope is also called the level 0 scope
- The scope that can be turned on by defining a function or code block is level 1/2/3 /… Scope (here are the key differences after ES6)
- JavaScript links these scopes together into a chain called the scope chain 0 –> 1 —-> 2 —-> 3 —-> 4
- Except for the level 0 scope, the current scope level is equal to the previous level +1
- The variable looks up rules in the scope chain
- First look at the current, found using the current scope found
- If not found in the current scope, go to the upper scope
- And so on up to level 0. If level 0 scope is not found, an error is reported
// Global scope/level 0 scope
let num = 123;
{
// Level 1 scope
let num = 456;
function test() {
// Level 2 scope
// let num = 789;
console.log(num);
}
test(); / / 456
}
Copy the code
Preparse, method
Preliminary analysis
- What is pre-parsing?
- Browsers execute JS code in two parts: pre-parsing and line-by-line execution
- That is, the browser doesn’t execute the code directly, it processes it,
- This process of processing is called pre-parsing
- Preresolution rule
- Promote variable and function declarations to the top of the current scope
- Place the rest of the code behind in the order you write it
- Pay attention to the point:
- Variables defined by let are not promoted (not pre-parsed)
Preparsing of variables
- Pre-parsing of variables declared by var
// Before preparsing
console.log(num); //undefined
var num = 123;
// After preparsing
var num;
console.log(num); //undefined
num = 123;
Copy the code
- Variables defined by let are not promoted (not pre-parsed)
Preparsing of functions
- Preparsing of orthodox functions
// The format of the function defined before ES6
say();
// The pre-ES6 format for defining functions is pre-parsed, so it can be called in advance
function say() {
console.log("hello 996");
}
// Pre-parsed code
function say() {
console.log("hello 996");
}
say();
Function say() {console.log("hello 996"); /* In Javascript, function say() {console.log("hello 996"); } * /
Copy the code
- The way functions are assigned to var variables is not preparsed (let even less so)
console.log(say); // undefined
say(); // say is not a function
var say = function() {
console.log("hello itzb");
}
// Pre-parsed code
console.log(say); // undefined
var say;
say(); // say is not a function
say = function() {
console.log("hello itzb");
}
Copy the code
- Arrow functions are not preparsed either.
say(); // say is not defined
let say = () = > {
console.log("hello itzb");
}
Copy the code
The dog title
Note: The browser executes pre-parsed code
- The pre-parsing rules are simple and smooth
var num = 123;
fun(); // undefined
function fun() {
console.log(num);
var num = Awesome!;
}
Var num; function fun() { var num; console.log(num); num = 666; } num = 123; fun(); // undefined */
Copy the code
var a = Awesome!;
test();
function test() {
var b = 777;
console.log(a); // The proximity principle of scope chains
console.log(b);
console.log(c); // Even if there is an error, the previous output will also be printed
var a = 888;
let c = 999;
}
/* after parsing: var a; function test() { var b; var a; b = 777; console.log(a); // undefined console.log(b); // 777 console.log(c); // error a = 888; let c = 999; } a = 666; test(); * /
Copy the code
- Advanced browsers do not promote functions defined in {}
if(true) {function demo() {
console.log("1"); }}else{
function demo() {
console.log("2");
}
}
demo(); / / 1
/ * pure logic: parsing, function, after writing covered writing first, then the output 2 practice: advanced browser not to ascend, {} the function defined in the then sequentially, output 1 * /
Copy the code
- If the scoped var variable name is the same as the function name, the function takes precedence over the variable. The logic of ‘covering’ has not been applied consistently.)
- It is important to remember that variable names and function names should never be the same in enterprise development
console.log(value); // Output function definition
var value = 123;
function value() {
console.log("fn value");
}
console.log(value); / / 123
Function value() {console.log("fn value"); function value() {console.log("fn value"); } console.log(value); var value; value = 123; console.log(value); * /
Copy the code
methods
Creating a default object
- JavaScript provides a default class Object that we can use to create objects
- Since we are creating objects using the system default class, the system does not know what properties and behaviors we want, so we have to manually add the desired properties and behaviors, right
- How to add attribute object names to an object. Attribute name = value;
- How to add a behavior object name to an object. Behavior name = function;
There are three ways to create objects
-
New one, add properties and methods to this object
let obj = new Object(a); obj.name ="fhs"; obj.age = 23; obj.say = function () { console.log("hello world"); } console.log(obj.name); console.log(obj.age); obj.say(); Copy the code
-
Assign an incomplete object (or even an empty object) to a variable
let obj = {}; // let obj = new Object(); The shorthand obj.name = "fhs"; obj.age = 23; obj.say = function () { console.log("hello world"); } console.log(obj.name); console.log(obj.age); obj.say(); Copy the code
-
Assign the complete object directly to the variable (key/value pairs are separated by colons and comma)
let obj = { name: "fhs".age: 23.say: function () { console.log("hello world"); }};console.log(obj.name); console.log(obj.age); obj.say(); Copy the code
Note:
Methods within an object should only be functions assigned to variables. Functions that exist within an object as orthodox functions are not methods of the object
The difference between functions and methods
The behavior of objects is called methods, not functions
-
What is a function? A function is one that is not bound to any other class display, and is called a function
-
What is method? Methods are explicitly bound to other classes, and we call them methods
-
The difference between functions and methods
- Functions can be called directly, but methods cannot be called directly, only through objects
- This inside the function outputs window, and this inside the method outputs the object currently called
-
Both functions and methods have something called this inside them
What is this? The current this is whoever called the current function or method
Factory function, constructor
I realize that the name of the constructor in JS is the so-called class name of JS
The factory function
What is a factory function? Factory functions are functions that are specifically used to create objects, and we call them factory functions
Effect: Reduces code redundancy
/* let obj = { name: "zs", age: 23, say: function () { console.log("hello world"); }}; let obj = { name: "xhx", age: 22, say: function () { console.log("hello world"); }}; * /
function createPerson(myName, myAge) {
let obj = new Object(a); obj.name = myName; obj.age = myAge; obj.say =function () {
console.log("hello world");
}
return obj;
}
let obj1 = createPerson("zs".23);
let obj2 = createPerson("xhx".22);
console.log(obj1);
console.log(obj2);
Copy the code
The constructor
The naive version constructor
- What is a constructor
- Constructors, like factory functions, are dedicated to creating objects
- Constructors are essentially shorthand for factory functions (with limited creation, more technical)
- The difference between constructors and factory functions
- Constructor function names must begin with a capital letter
- Constructors can only be called with new
function Person(myName, myAge) {
// let obj = new Object(); // The system automatically added it
// let this = obj; // The system automatically added it
this.name = myName;
this.age = myAge;
this.say = function () {
console.log("hello world");
}
// return this; // The system automatically added it
}
let obj1 = new Person("zs".23);
let obj2 = new Person("xhx".22);
console.log(obj1);
console.log(obj2);
Copy the code
When we new Person(” Zs “, 23); What does the system do?
- An object is automatically created in the constructor
- The object you just created is automatically assigned to this
- Return this is automatically added at the end of the constructor;
- Notice that if we manually complete the part of the constructor that JS automatically added for us, it becomes a factory function
Optimization constructor
Why optimize
- The say method in both objects is implemented the same, but stored in different storage Spaces, which causes poor performance
- Optimize to improve performance
First edition optimization
The drawbacks of the current approach
- Reading is reduced
- Contaminate the global namespace
function mySay() {
console.log("hello world");
}
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = mySay;
}
let obj1 = new Person("zs".23);
let obj2 = new Person("xhx".22);
// Check whether two functions are stored in the same block of memory
console.log(obj1.say === obj2.say); // true
Copy the code
Second Edition optimization
FNS stands for Function Name Space, and HHH isn’t much of an improvement on the first version
// function mySay() {
// console.log("hello world");
// }
let fns = {
mySay: function () {
console.log("hello world"); }}function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = fns.mySay;
}
let obj1 = new Person("zs".23);
let obj2 = new Person("xhx".22);
console.log(obj1.say === obj2.say); // true
Copy the code
Version 3 Optimization (Getting started with Prototyping)
Prototype is the object, and in this case prototype is the object of the constructor object
With prototypes, it is truly pollution-free, but there is a certain threshold for readability
I tried it out in Chrome, and constructors are essentially the same as normal functions
// let fns = {
// mySay: function () {
// console.log("hello world");
/ /}
// }
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
Person.prototype = { Person. Prototype. Say = function (){
say: function () {
console.log("hello world"); }}let obj1 = new Person("zs".23);
let obj2 = new Person("xhx".22);
console.log(obj1.say === obj2.say); // true
Copy the code
Addendum: This is called custom prototype objects on line 10, and the comment section on line 10 is called dynamically adding methods to prototype objects