catalogue
1, Change the direction of this in the function
3. Differences among VaR, let and const
5, ES6 deconstruction assignment
7, Remaining parameters and extension operators
1. Remaining parameters (...args)
two Extension operator (expand syntax)
1, Change the direction of this in the function
Before talking about the method, let's first understand several situations of this point.
Call mode | this point |
---|---|
Ordinary function call | window |
constructor call | The methods in the instance object prototype object also point to the instance object |
Object method call | The object to which the method belongs |
Event binding method | Bind event object |
Timer Functions | window |
Execute function now | window |
These points of this are determined when we call the function. Different calling methods determine the different direction of this, which generally points to our caller
1. call()
var o = { name: 'andy' } function fn(a,b) { console.log(this); console.log(a + b); }; fn.call(o,1,2); // this points to object o, and the output is {name:'andy'} 3
effect:
1.call the first function that can be called The second one can change the point of this in the function
2. The main function of call is to realize inheritance
Inheritance case code:
function Father(uname,age,sex) { this.uname = uname; this.age = age; this.sex = sex; } function Son(uname,age,sex) { Father.call(this,uname,age,sex); //It is equivalent to inheriting the parent class and setting its own properties } var son = new Son('Lau Andy',18,'male'); //The print result is Andy Lau, 18 male
2. apply()
The apply() method calls a function. It is simply understood as the way to call a function, but it can change the this point of the function.
fun.apply(thisArg, [argsArray])
thisArg: the value of this specified when the fun function runs
argsArray: the passed value must be contained in the array (pseudo array)
The return value is the return value of the function, because it is the calling function
var o = { name: 'andy' }; function fn(arr) { console.log(this); console.log(arr); }; fn.apply(o,['pink']); //this points to o, and the output is {name:'andy'} pink
Note: the main application of apply For example, we can use apply to find the maximum / minimum value with the help of mathematical built-in objects
The code is as follows 👇
var arr = [1,66,3,99,4]; var max = Math.max.apply(Math,arr); //The first parameter of apply is null or points to the Math built-in object, because it is the max function called by Math, which is better console.log(max); //The result is 99
3. bind() ⭐
The bind() method does not call the function, but it can change the internal this point of the function
fun.bind(thisArg, arg1,arg2,...)
thisArg: the value of this specified when the fun function runs
arg1,arg2: other parameters passed
Returns a copy of the original function modified by the specified this value and initialization parameters
var o = { name: 'andy' }; function fn(a,b) { console.log(this); console.log(a+b); }; var f = fn.bind(o,1,2); f();
Note: if f is used to receive the copied function, the object pointed to by this can be output by calling. If it is not called, it will not be output
The bind() method is used with the timer as follows 👇 (when the button is pressed, the button changes to non clickable state and recovers after three seconds)
var btn1 = document.querySelector('button'); btn1.onclick = function(){ this.disabled = true; //This this points to the btn button setTimeout(function(){ this.disabled = false; //Originally, this in the timer function should point to window, but because bind is called, it points to btn }.bind(this),3000); //This this points to the btn object }
4. Summary of three methods
Similarities:
Can change the this point inside the function
Differences:
1. call and apply will call the function and change the internal this point of the function
2. The parameters passed by call and apply are different. The parameters passed by call are in the form of aru1,aru2.. and apply must be in the form of array [arg]
3. bind will not call the function. You can change the internal this point of the function
Main application scenarios:
1. call often does inheritance
2. apply is often related to arrays, such as realizing the maximum and minimum values with the help of mathematical objects
3. bind does not call the function, but also wants to change the this point, such as changing the this point inside the timer
2, Closure
A closure is a function that has access to a variable in the scope of another function
A simple understanding is that a scope can access local variables inside another function
for instance 👇
function fn() { var num = 5; function fun() { console.log(num); } fun(); } fn(); //The output is 5
Obviously, fn and fun have different scopes, but fun can access local variables in fn, so fn is a closure
The main function of closures is to extend the scope of variables. Local variables will not be destroyed until all functions have called the local variables
Frequently asked interview questions of closures: use closures to get the index number of the current small li
var lis = document.querySelectorAll('li'); for(var i = 0; i < lis.length;i++) { //Four immediate execution functions are created using the for loop //The immediate execution function is also called a small closure because any function in the immediate execution function can use its i variable (function(i){ lis[i].onclick = function() { console.log(i); } })(i); }
However, this method is more complex and troublesome than creating custom attributes, because this method creates multiple immediate execution functions, and each local variable i must be released after the click event. If it is not clicked, it will not be released, resulting in memory leakage.
therefore Closures are not necessarily good. They should be used reasonably
3, Recursion
What is recursion?
If a function can call itself internally, the function is a recursive function
Simple understanding: the function calls itself internally. This function is a recursive function
Recursive functions have the same effect as loops
Because recursion is prone to "stack overflow", an exit condition return must be added
Because recursion is a little around, the blogger was dizzy several times when he started learning, so the blogger will give more examples. If you can understand them, it means that you have mastered them very well~
① Using recursive function to find factorial 1 * 2 of 1~n * 3 * 4 ...n
function fn(n) { if(n == 1) { return 1; } return n * fn(n-1); //Suppose that n = 3 is passed in, first judge whether n is equal to 1, which is not equal to executing return n* fn(n-1); //Therefore, the result of the first entry is return 3 * fn(3-1); //fn(3-1) enters the function again and continues to judge that it is not equal to 1, so the return value is 2 * fn(2-1); //fn(2-1) continue calling the function. At this time, n = 1, return 1 // Replace all fn(n-1) above with the value returned by return as: 3 * 2 * 1 = 6 } console.log(fn(3));
② Using recursive function to find Fibonacci sequence (rabbit sequence) 1, 1, 2, 3, 5, 8, 13, 21
//We only need to know the first two items (n-1, n-2) of N entered by the user to calculate the sequence value corresponding to n function fb(n) { if( n ===1 || n ===2) { return 1; } return fb(n-1) + fb(n-2); } console.log(fb(3));
② The running steps are the same as ①. You can try to write them on the draft. If you can do both of the above, let's see how recursion traverses the data
③ Enter the id number to return the corresponding data object
var data = [{ id:1, name: 'household electrical appliances', goods:[{ id:11, gname: 'Refrigerator' },{ id:12, gname: 'Washing machine' }] },{ id:2, name: 'Clothes & Accessories' }]; function getID(json,id) { var o = {}; json.forEach(function(item){ if(item.id == id) { o = item; // return item; } else if (item.goods && item.goods.length > 0) { o = getID(item.goods, id); } }); return o; } console.log(getID(data,1)); console.log(getID(data,2)); console.log(getID(data,11));
4, let and const in ES6
Why use ES6:
The birth of each standard means the improvement of the language and the strengthening of functions. JavaScript language itself also has some unsatisfactory places
The variable promotion feature increases the unpredictability of program runtime
The syntax is too loose. Different people may write different code to achieve the same function
1. let keyword
Keywords added in ES6 for declaring variables, let declared variables are only valid at the block level
if(true) { let a = 10; } console.log(a) // a is not defined
be careful: ❗
① Only variables declared with let keyword have block level scope, and variables declared with var do not have block level scope
Benefit: prevent circular variables from becoming global variables
for(let i = 0; i < 5; i++) { } console.log(i); // i is not defined
② There is no variable promotion
console.log(a); // a is not defined let a = 20;
③ Temporary deadband (variables with the same name defined externally have no effect on the let of the block level scope);
var tmp = 123; if(true) { tmp = 'abc'; let tmp; console.log(tmp);// tmp is not defined }
let keyword interview questions 👇
👆 var defined variables, 👇 let defined variables
2. const keyword
Function: declare a constant. A constant is an amount whose value (memory address) cannot be changed
characteristic: ❗
① With block level scope
if(true) { const a = 10; } console.log(a); // a is not defined
② A value must be assigned when declaring a constant
const PI; //Missing initializer in const declaration
③ After constant assignment, the value cannot be modified. For complex data types, such as arrays, it is possible to change the contents of the corresponding index number Yes, but re assignment is not enough, that is, the memory address cannot be changed
const ary = [100,200]; ary[0] = 'a'; ary[1] = 'b'; console.log(ary); // ['a','b']; ary = ['a','b']; // Assignment to constant variable
3. Differences among VaR, let and const
var | let | const |
---|---|---|
Function level scope | Block level scope | Block level scope |
Variable promotion | There is no variable promotion | There is no variable promotion |
The value can be changed | The value can be changed | The value cannot be changed |
5, ES6 deconstruction assignment
ES6 allows you to extract values from the array and assign values to variables according to their corresponding positions. Objects can also be deconstructed
1. Array deconstruction
let [a,b,c] = [1,2,3]; console.log(a); // 1 console.log(b); // 2 console.log(c); // 3
If the deconstruction is unsuccessful, the value of the variable is undefined 👇
let [bar,foo] = [1]; console.log(foo); // undefined console.log(bar); // 1
2. Object deconstruction
let person = {name: 'zhangsan', age: 20}; let {name,age} = person; console.log(name); // 'zhangsan' console.log(age); // 20 //----------------Writing method 2 👇-------------- let {name: myName,age: myAge} = person; //myName myAge belongs to alias console.log(myName); // 'zhangsan' console.log(myAge); // 20
6, ES6 arrow function
Arrow functions are used to simplify the function definition syntax
() => {}
const fn = () => {}
characteristic: ❗
① There is only one sentence of code in the function body, and the execution result of the code is the return value. Curly braces can be omitted
function sum(num1,num2) { return num1 + num2; } //----------The following code is equivalent to the above------ const sum = (num1,num2) => num1 + num2;
② If there is only one formal parameter, you can omit the parentheses
function fn(v){ return v; } //--------The following code is equivalent to the above-------- const fn = v => v;
this in arrow function
The arrow function does not bind the this keyword. This in the arrow function points to the context this of the function definition position
const obj = {name: 'zhangsan'} function fn() { console.log(this); return () => { console.log(this) } } const resFn = fn.call(obj); resFn(); // this points to obj and the output is {name: 'zhangsan'}
Arrow function interview question
var obj = { age: 20, say: () => { alert(this.age) } } obj.say(); //The output is undefined
obj object cannot generate scope, so this is equivalent to being defined under the global scope, so the return value is undefined
7, Remaining parameters and extension operators
1. Remaining parameters (...args)
① Remaining parameters... args allows us to represent an indefinite number of parameters as an array
function sum(first, ...args){ console.log(first); //10 console.log(args); // [20,30] } sum(10,20,30)
② Put all the obtained values into an array, and then use forEach to traverse, so that different numbers of arguments can be passed in
const sum = (...args) => { let total = 0; args.forEach(item => total += item); return total; }; console.log(sum(10,20)); // 30 console.log(sum(10,20,30)); //60
The remaining parameters are used with deconstruction
Just prefix the variable ... It means that this is an array, which is used to receive the remaining parameters
let students = ['wangwu','zhangsan','lisi']; let [s1, ...s2] = students; console.log(s1); // 'wangwu' console.log(s2); // ['zhangsan','lisi']
two Extension operator (expand syntax)
The extension operator can convert an array or object into a comma separated sequence of parameters
Just add... Before the array name or object name
let ary = [1,2,3]; ...ary // 1,2,3 console.log(...ary); // 1 2 3 //There is no comma separation when outputting console.log, because the comma of parameter sequence is used as the parameter separator of console.log method, which is equivalent to console.log(1,2,3); So the output is 1 2 3
Extension operator application: merging arrays
// Method 1 let ary1 = [1,2,3]; let ary2 = [3,4,5]; let ary3 = [...ary1, ...ary2]; // Method 2 ary1.push(...ary2);
Application of extension operator: convert pseudo array to real array
[pseudo array is similar to: many div tags obtained from the page are stored in the pseudo array and converted into an array You can call the methods in the array]
let oDivs = document.getElementsByTagName('div'); oDivs = [...oDivs];
8, Array instance method
1. Array.from()
Converts a class array or traversable object to a real array
let arrayLike = { '0':'a', '1':'b', '2':'c' }; let arr2 = Array.from(arrayLike); // ['a','b','c']
Method can also accept the second parameter, which is similar to the map method of array. It is used to process each element and put the processed value into the returned array
let arrayLike = { '0': 1, '1': 2, 'length': 2 } let newAry = Array.from(aryLike,item => item * 2) // item is the currently traversed object. Multiply the value of each object by 2
2. find()
Used to find the first qualified array member. If it is not found, it returns undefined
let ary = [{ id: 1, name: 'Zhang San' }, { id: 2, name: 'Li Si' }]; let target = ary.find((item,index) => item.id == 2); console.log(target); // {id: 2, name: "Li Si"}
3. findIndex()
Used to find the position of the first qualified array member. If it is not found, it returns - 1
let ary = [1,5,10,15]; let index = ary.findIndex((value, index) => value > 9); console.log(index); //2
4. includes()
Indicates whether an array contains a given value and returns a Boolean value
[1,2,3].includes(2) //true [1,2,3].includes(4) //false
9, set data structure
1. startsWith(),endsWith()
startsWith(): indicates whether the parameter string is at the head of the original string and returns a Boolean value
endsWith(): indicates whether the parameter string is at the end of the original string and returns a Boolean value
let str = 'Hello world!'; str.startsWith('Hello') // true str.endsWith('!') // true
2. repeat()
The repeat method repeats the original string n times and returns a new string
'x'.repeat(3) //'xxx' 'hello'.repeat(2) // 'hellohello'
3. Set data deconstruction
ES6 provides a new data structure Set. It is similar to array, but the values of members are unique and there are no duplicate values
Set itself is a constructor used to generate a set data structure
const s = new Set();
The Set function can accept an array as a parameter to initialize
const set = new Set([1,2,3,4]);
Deconstruction of Set data for array de duplication
const s3 = new Set(['a','a','b','b']); console.log(s3.size) // Because the repeated part will be removed const ary = [...s3]; console.log(ary) //['a','b']
Set instance method
add(value): adds a value and returns the Set structure itself
delete(value): deletes a value and returns a Boolean value indicating whether the deletion is successful
has(value): returns a Boolean value indicating whether the value is a member of Set
clear(): clear all members without return value
const s = new Set(); s.add(1).add(2).add(3); //Adds a value to the set structure s.delete(2) //Delete the 2 value in the set structure s.has(1) //Indicates whether the set structure has 1. This value returns a Boolean value s.clear() //Clear all values in the set structure
Traversal Set
Like an array, an instance of a Set structure also has a forEach method to perform certain operations on each member without returning a value
s.forEach(value => console.log(value))
This sharing is over~