preface

“Although you martial arts pattern many, but bo but not fine, miscellaneous and not pure, you exactly so martial arts the most exquisite, specialized, lian to such as fire pure qing, it is possible to defeat Guo Jing”. I have been watching a lot of blogs and practicing a lot of small and large demos, but I have no systematic arrangement, so I am not accustomed to it. Just because it takes a lot of effort to learn the front end, it’s time to comb through what you’ve learned. JavaScript>Vue>CSS>HTML>Java, in this order, just to give yourself a pressure to start some of your own blog. 2020-1, tall and handsome full stack. 😄 😄 😄 😄

The source address

The resources

Ruan Yifeng ES6 introduction

MDN JavaScript

This wave can counter-kill -JavaScript advanced series

Liu Xiaoxi’s blog

Online Babel

API

String

/ / 1.
const str1 = 'Fury';
console.log(typeof str1); // string
console.log(str1 instanceof String);
// 2. Constructor
const str2 = new String('Fury');
console.log(typeof str2); // object
// 3. String comparison logic judgment
// If the string is not an empty string, press true
console.log(' '= =false); // true
console.log(' '= = =false); // false
console.log('a'= =true); // true
Copy the code

String.prototype.charAt

// 3.String.prototype.charAt
const str3 = 'Fury';
const ret3 = str3.charAt(3);
console.log(ret3); // y
const ret4 = str3.charAt(10);
console.log(ret4); / /"
Copy the code

String.prototype.fromCharCode

/** * 5. * const str = String.prototype.fromCharCode(num1, ... , numN) * @description: STRING created by the specified UTF-16 code unit sequence. * @param {Number} num Specifies a sequence of utF-16 code units. The value ranges from 0 to 65535 * @ RETURNS {String} STR A String of N characters consisting of N specified UTF-16 code units. */
console.log(String.fromCharCode(65.66.67)); // ABC
console.log(String.fromCharCode(0x2014)); // -
console.log(String.fromCharCode(0x12014)); // -
Copy the code

String.prototype.concat

/** * @author: Const STR = string.prototype. Concat (string2, string3[,... StringN]) * @param {String} stringN: multiple strings linked to the source String * @returns {String} STR: a new String returned after the link, the original String remains unchanged * @description: Merges one or more strings with the original string concatenation to form a new string and returns. * /
const name = 'Gulas Joseph Fury:';
const name1 = 'Nicholas ';
const name2 = 'Joseph ';
const name3 = 'Fury ';
const ret5 = name.concat(name1, name2, name3);
console.log(name); // Gulas Joseph Fury:
console.log(name1); // Nicholas
console.log(name2); // Joseph
console.log(name3); // Fury
console.log(ret5); // Nicholas Joseph Fury
Copy the code

String.prototype.includes

/** * @author: Zhang qin * const climbing bool = String. Prototype. Includes (searchString, fromIndex = [0]) * @ param {String} searchString: to search String in this String. * @param {Number} fromIndex: starts at some index position, * @description: used to determine whether a string is contained in another string, returning true or false depending on the case. * /
console.log('Blue Whale'.includes('lu')); // true
console.log('Blue Whale'.includes('lu'.2)); // false
Copy the code

String.prototype.endsWith

/** * @author: Zhang qin * const climbing bool = String. The prototype. The endsWith (searchString [, Length =str.length]) * @param {String} searchString: The String to search in this String. * @param {Number} length: specifies the length of a string. * @description: specifies whether the current string is "terminated" by another given substring. Returns true or false depending on the result. * /
const str11 = 'i love you three thousand times';
console.log(str11.endsWith('times')); // true
console.log(str11.endsWith('i'.1)); // true
Copy the code

String.prototype.indexOf

/** * @author: Const index= string.prototype.indexof (searchValue[, fromIndex]) * @description: const index= string.prototype.indexof (searchValue[, fromIndex]) * @description: Search from fromIndex. If no fromIndex is found, -1 is returned. * @param {String} searchValue: A String representing the value being searched. * @param {Number} fromIndex: the index to start the query * @returns {Number} index: the index for the first occurrence of the specified value; If I don't find negative 1. * /
const str12 = 'i love you three thousand times';
console.log(str12.indexOf('l')); / / 2
console.log(str12.indexOf('l'.3)); // -1
console.log(str12.indexOf('l'.1 - str12.length)); / / 2
Copy the code

String.prototype.lastIndexOf

/** * @author: Zhang qin * climbing const index = String. The prototype. The lastIndexOf (searchValue [, EndIndex =str.length-1]) * @description: the index of the searchValue for the first time. * @param {String} searchValue: a String representing the value being searched. * @param {Number} endIndex: the end of the string at the index * @returns {Number} index: the index of the first occurrence of the specified value; If I don't find negative 1. * /
const str13 = 'i love you three thousand times';
console.log('str13 The string contains: ', str13.length); / / 31
console.log(str13.lastIndexOf('times')); / / 26
console.log(str13.lastIndexOf('s')); / / 30
// Actually find 'I love'
console.log(str13.lastIndexOf('ve '.6)); / / 4
// Actually find 'I love'
console.log(str13.lastIndexOf('ve'.5)); / / 4
/ /
console.log(str13.lastIndexOf('i'.1 - str13.length)); / / 0
console.log(str13.lastIndexOf('i'.- 1)); / / 0
Copy the code

String.prototype.toLowerCase

String.prototype.toUpperCase

/** * @author: Zhang qin * const climbing STR = String. Prototype. ToLowerCase () String to lower case back, Does not affect the original * const String STR = String. The prototype. The toUpperCase () the String to turn the capital return, do not affect the original String * @ description: * /
const str14 = 'abcDGE zhang';
const ret14 = str14.toLowerCase();
console.log(ret14); / / abcdge zhang
const ret15 = str14.toUpperCase();
console.log(ret15); / / ABCDGE zhang
Copy the code

String.prototype.match

/** * @author: Const ret = string.prototype. Match (regexp) * @param {regexp} regexp: regex * @returns {Array} ret Its contents depend on the presence or absence of the Global (g) flag, or null if no match is found. * Groups: An array of capture groups or undefined (if no named capture group is defined). * index: start position of matched result * input: search string * @description: */
// 1. The regular expression with g is matched from the rest of the string. Match as many rules as possible.
const str1 = 'aaaa1aaaa1aaaa';
const ret1 = str1.match(/aa/g);
console.log(ret1); // ['aa', 'aa', 'aa', 'aa', 'aa', 'aa'];
// Match as many rules as possible
const ret2 = str1.match(/aa*/g);
console.log(ret2); // [ 'aaaa', 'aaaa', 'aaaa' ]

// 2. Regular expression without g, match as many first ones as possible, and return data
const str3 = 'aaaa1aaaa1aaaa';
const ret3 = str3.match(/aa/);
console.log(ret3); // [ 'aa', index: 0, input: 'aaaa1aaaa1aaaa', groups: undefined ]
console.log(ret3[0]); // aa
// The starting position of the matching result
console.log(ret3.index); / / 0
// Search for the string.
console.log(ret3.input); // aaaa1aaaa1aaaa
// An array of capture groups or undefined (if no named capture group is defined).
console.log(ret3.groups); // undefined

const ret4 = str3.match(/aa*/);
console.log(ret4); // [ 'aaaa', index: 0, input: 'aaaa1aaaa1aaaa', groups: undefined ]

// 3. Operation string
const ret5 = str3.match('aaa');
console.log(ret5); // [ 'aaa', index: 0, input: 'aaaa1aaaa1aaaa', groups: undefined ]

Copy the code

String.prototype.replace

/ * * * @ author: zhang qin * const climbing ret = String. The prototype, the replace (regexp, newSubStr | function) * @ the description: Replaces part of a string that conforms to the regular expression, returning the new string without changing the original string. * @param {RegExp} RegExp: regular expression * @param {String} newSubStr: matching result is replaced with the corresponding String * @param {Function} Function: matching result executes the callback Function * @returns {String} ret Returns a new String */ after the String instance is replaced
// 1. Return a new string without changing the original string.
const str1 = 'Carol, the night';
const ret1 = str1.replace('Carol'.'Alisa');
console.log(str1); // Carol, the night
console.log(ret1); // Alisa, the night

// 2. Match the regular expression, without g, and replace only the first one that matches the rule
const str2 = 'aaaa1saaaa1saaaa';
const ret2 = str2.replace(/aaaa/.'Carol');
console.log(ret2); // Carol1saaaa1saaaa

// 3. Matches the regular expression with g.
const str3 = 'aaaa1saaaa1saaaa';
const ret3 = str3.replace(/aaaa/g.'Carol');
console.log(ret3); // Carol1sCarol1sCarol

String. Prototype. replace(regexp, callback(match,p1[,p2,... ),offset,string) * @param {string} match: matching substring * @param {} pn regular expression, When grouping, each matched result * @param {Number} offset: index of the matched substring in the original String * @param {String} String: instance of the operation method */
const str4 = 'aaaa1saaaa1saaaa';
const ret4 = str4.replace(/(aaaa)(1s)/g, (match, p1, p2, offset, string) => {
    console.log(match); // aaaa1s
    console.log(p1); // aaaa
    console.log(p2); // 1s
    console.log(offset); / / 0
    console.log(string); // aaaa1saaaa1saaaa
    return `${match}M`;
});
console.log(ret4);

Copy the code

String.prototype.search

/** * @author: const index = string.prototype. Search (regexp) * @description: const index = string.prototype. * @param {RegExp} RegExp: RegExp is a regular expression * @returns {Number} index: returns an index if a match is found. If no match is found, -1 is returned. * /
/ / 1.
const str1 = 'aaaa1aaaa1aaaa';
const index1 = str1.search(/1aa/g);
console.log(index1); / / 4
const index2 = str1.search('ax');
console.log(index2); // -1

Copy the code

String.prototype.slice

/** * @author: const ret = string.prototype. Slice (beginIndex[, endIndex]) * @description: * @param {Number} beginIndex: start index * @param {Number} endIndex: endIndex, excluding technical index. Default str.length * @returns {String} ret: returns a new String after interception. * /
// 1. Normal parameter transfer
const str = 'abcdefg';
const ret = str.slice(1);
console.log(ret); // bcdefg
const ret1 = str.slice(2.5);
console.log(ret1); // cde
// 2. Pass a negative number (index - string length) equal to negative index -3 for e and -1 for g, but not the end index
const ret3 = str.slice(- 3.- 1);
console.log(ret3); // ef

Copy the code

String.prototype.split

/** * @author: const arr = string.prototype. Split ([separator[, limit]]) * @description: Separator: a string or regular expression * @param {Number} limit: an integer * @returns {Array} arr: returns results after splitting */
// 1. Normal parameter transfer
const str = 'a12b12c12d12e12f12g';
const ret = str.split(/ 12 /);
console.log(ret); // [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]
const ret1 = str.split(/ 12 /.3);
console.log(ret1); // [ 'a', 'b', 'c' ]

Copy the code

String.prototype.substring

/ * * * @ author: zhang qin * const climbing STR = String. The prototype, the substring (indexStart [indexEnd]) * @ the description: @param {Number} indexStart: start index * @param {Number} indexEnd: end index * @returns {String} STR: returns a new string */ after interception
// 1. Normal parameter transfer
const str = 'abcdefg';
const ret = str.substring(1);
console.log(ret); // bcdefg
const ret1 = str.substring(2.5);
console.log(ret1); // cde
// 2. Pass a negative number (index - string length) equal to negative index -3 for e and -1 for g, but not the end index
const ret3 = str.substring(- 3.- 1);
console.log(ret3); // "empty string

Copy the code

Array

Array.from()

/* eslint-disable prefer-rest-params */
/** * @author: @description: array.from () creates a new Array instance from an array-like or iterable. * @param arrayLike: a pseudo-array object or iterable that you want to convert to an array. String, array, Set,Map * @param {Function} mapFn: If specified, each element in the new array will execute the callback Function. * @param {Object} thisArg: This Object is optional when the callback mapFn is executed. * If mapFn is an arrow function, this in the arrow function is not thisArg. Const Array = array. from(arrayLike[, mapFn[, thisArg]]) */
// 1. Array.from Operation string
const arr = Array.from('Tall and handsome full stack');
console.log(arr); // [' so ', 'so ',' so ', 'so ',' so ', 'so ',' so ']

// 2, array. from Set, which can also be used to deduplicate arrays
const obj = Array.from(new Set([1.2.1.3]));
console.log(obj); // [1, 2, 3]

// 3, array. from operation Map
const map = new Map(a); map.set('name'.'张');
map.set('function', (data) => {
    console.log(data);
});
const fromMap = Array.from(map);
console.log(fromMap); / / [[' name ', 'a'], [' function '[function]]]

// array.form ()
function f1() {
    return Array.from(arguments);
}
f1(1.2.3); // [1, 2, 3]

// 5, Array
const arrFromAllArguments = Array.from(
    [1.2.3].{num:2}}
    function mapFn(x) {
        return x * this.num;
    },
    { num: 2});console.log(arrFromAllArguments); // [2, 4, 6]
Copy the code

Array.isArray()

/* eslint-disable no-array-constructor */
/** * @author: zhang Panqian * @description: array.isarray () used to determine whether the value passed is an Array. * @param {*} obj: the variable to be detected * @RETURNS {Boolean} bool: If obj is Array,bool is true. * const bool=Array.isArray(obj) */
// The following function calls all return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(Array.prototype);
Copy the code

Array.of

/* eslint-disable no-array-constructor */
/** * @author: Zhang Panchen * @description: array.of () creates a new Array instance with a variable number of arguments, regardless of the number or type of arguments. * @param {*} elementN: Any arguments that will become elements in the returned array in that order. * @returns {Array} Array: new Array instance. * const array=Array.of(element0[, element1[, ...[, elementN]]]); * /
/ / 1.
const arr = Array.of(7);
console.log(arr); / / [7]
/ / 2.
const arr1 = Array.of(1.2.3);
console.log(arr1); / / [1, 2, 3]
/ / 3.
const arr2 = Array(7);
console.log(arr2); // [,,,,,,]
/ / 4.
const arr3 = Array(1.2.3);
console.log(arr3); / / [1, 2, 3]
/ / 5.
const obj = [1.2.3.4];
const arr4 = Array.of(obj);
console.log(arr4); [[1, 2, 3, 4]]
/ / 6.
const arr5 = Array.of(... obj);console.log(arr5); // [1, 2, 3, 4]
Copy the code

Array.prototype.concat

/** * @author: const newArray= array.prototype. Concat (value1[, value2[,...[, valueN]]]) * @description: Array.prototype.concat concatenates an Array and returns a new Array. I'm not going to change the array. * @param {*} value: element to be added * @returns {Array} newArray: newArray after connection */
/ / 1.
const arr = [1.2.3];
const arr2 = [4.5.6];
const ret = arr.concat(arr2);
console.log(arr); // [1, 2, 3]
console.log(arr2); // [4, 5, 6]
console.log(ret); // [1, 2, 3, 4, 5, 6]
// 2. This is recommended
const ret2 = [...arr, ...arr2];
console.log(arr); // [1, 2, 3]
console.log(arr2); // [4, 5, 6]
console.log(ret2); // [1, 2, 3, 4, 5, 6]

Copy the code

Array.prototype.every

/** * @author: const bool = array.prototype. Every ([item[,index[, Array]]])[, thisArg]) * @description: Whether all elements in an array pass a test for a given function. Returns true. * @param {Function} callback: callback([item[,index[,array]]]) * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {Boolean} bool: Each callback returns true, and finally returns true. * /
// 1. Normal argument, arrow function cannot bind this
const arr1 = [2.3];
const thisArg = { name: 'Thor' };
const ret1 = arr1.every((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return item > 2;
}, thisArg);
console.log('Operation value', ret1); // false
// 2. Normal argument, normal function binding this
const arr2 = [2.3];
const ret2 = arr2.every(function _every(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
    return item > 2;
}, thisArg);
console.log(ret2); // false

Copy the code

Array.prototype.filter

/** * @author: const arr = array.prototype. Callback ([item[,index[, Array]]])[, thisArg]) * @description: /** * @author: const arr = array.prototype. Whether all elements in an array pass a test for a given function. Returns true. * @param {Function} callback: callback([item[,index[,array]]]) * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {Array} arr: returns the element that matches the assertion. * /
// 1. Normal argument, arrow function cannot bind this
const arr1 = [2.3.6.4.9.8];
const thisArg = { name: 'Thor' };
const ret1 = arr1.filter((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return item > 4;
}, thisArg);
console.log('Operation value', ret1); // [6, 9, 8]
// 2. Normal argument, normal function binding this
const ret2 = arr1.filter(function _every(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
    return item > 4;
}, thisArg);
console.log('Operation value', ret2); // [6, 9, 8]

Copy the code

Array.prototype.find

/** * @author: const item = array.prototype. Find (callback([item[,index[, Array]]])[, thisArg]) * @description: /** * @author: const item = array.prototype. Returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined. * @param {Function} callback: callback([item[,index[,array]]]) * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {*} item: the first element that satisfies the condition. * /
// 1. Normal argument, arrow function cannot bind this
const arr1 = [4.2.4.43.4];
const thisArg = { name: 'Thor' };
const ret1 = arr1.find((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return item > 2;
}, thisArg);
console.log('Operation value', ret1); / / 4
// 2. Normal argument, normal function binding this
const ret2 = arr1.find(function _every(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
    return item > 2;
}, thisArg);
console.log(ret2); / / 4

Copy the code

Array.prototype.findIndex

/** * @author: Zhang qin * climbing const index = Array. Prototype. FindIndex (callback ([item [, index, Array []]]], [thisArg]) * @ the description: Returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned. * @param {Function} callback: callback([item[,index[,array]]]) * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {Number} index: the index of the first element that meets the condition. * /
// 1. Normal argument, arrow function cannot bind this
const arr1 = [4.2.4.43.4];
const thisArg = { name: 'Thor' };
const ret1 = arr1.findIndex((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return item > 2;
}, thisArg);
console.log('Operation value', ret1); / / 0
// 2. Normal argument, normal function binding this
const ret2 = arr1.findIndex(function _every(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
    return item > 2;
}, thisArg);
console.log(ret2); / / 0

Copy the code

Array.prototype.forEach

/** * @author: const obj = array.prototype. ForEach ([item[,index[, Array]]])[, thisArg]) * @description: /** * @author: const obj = array.prototype. Executes the provided function once on each element of the array. * @param {Function} callback: callback Function * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {undefined} obj: undefined */
// 1. Normal argument, arrow function cannot bind this
const arr1 = [2.3];
const thisArg = { name: 'Thor' };
arr1.forEach((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
}, thisArg);
// 2. Normal argument, normal function binding this
const arr2 = [2.3];
arr2.forEach(function _forEach(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
}, thisArg);

Copy the code

Array.prototype.includes

/** * @author: @description: This method is used to determine whether an array contains a specified value, and returns true if it does, or false otherwise. * @param {*} valueToFind: variable to be determined * @param {Number} Optional. FromIndex index at the start of fromIndex. * @returns {Boolean} bool Returns true. * const bool = Array.prototype.includes(valueToFind[, fromIndex]); * /
/ / 1.
const arr = [1.2.3];
const ret1 = arr.includes(1);
console.log(ret1); // true
/ / 2,
const ret2 = arr.includes(1.1);
console.log(ret2); // false
// 3, index - array length can be negative index
const ret3 = arr.includes(2.2 -);
console.log(ret3); // true
// 4, index -
const ret4 = arr.includes(1.2 -);
console.log(ret4); // false
// 5, index is negative, absolute value is greater than the array length, the entire array search
const ret5 = arr.includes(1.- 5);
console.log(ret5); // true

Copy the code

Array.prototype.indexOf

/** * @author: const index = array.prototype. IndexOf (searchElement[, fromIndex = 0]) * @description: Returns the first index in the array where a given element can be found, or -1 if none exists. @param {*} searchElement: searchElement * @param {Number} fromIndex: start index * @returns {Number} index: return index of a given element */
// 1. Normal parameters
const arr1 = [2.3.4.5.6];
const index1 = arr1.indexOf(3);
console.log(index1); / / 1
const index2 = arr1.indexOf(3.2);
console.log(index2); // -1

Copy the code

Array.prototype.join

/** * @author: const string= array.prototype. Join ([separator]) * @description: Array.prototype.join links the element to a string and returns this string. * @param {String} separator: Specifies the String to separate the element. Default: ", "* @returns {String} String: specifies the String to connect all array elements. If arr.length is 0, an empty string is returned. * /
// 1
const arr1 = [1.2.3];
const str1 = arr1.join();
console.log(str1); / / 1, 2, 3
// 2. Link string
const arr2 = ['L'.'o'.'k'.'i'];
const str2 = arr2.join(' ');
console.log(str2); // Loki
// 3. Link objects
const arr3 = [{ name: 'Loki' }, { name: 'Loki' }, { name: 'Loki' }];
const str3 = arr3.join();
console.log(str3); // [object Object],[object Object],[object Object]

Copy the code

Array.prototype.keys

/* eslint-disable no-restricted-syntax */
/** * @author: const iterator = array.prototype.keys () * @description: Returns an Array iterator containing each index key in the Array. Returns {Iterator} Iterator: new Iterator object */
// 1. Normal argument, arrow function cannot bind this
const arr1 = [4.2.4.43];
const obj = arr1.keys();
for (const index of obj) {
    console.log(index); / / expected output: 0,1,2,3
}

Copy the code

Array.prototype.lastIndexOf

/** * @author: Zhang qin * climbing const index = Array. The prototype. The lastIndexOf (searchElement [, fromIndex = arr. Length - 1]) * @ the description: Returns the first index in the array where a given element can be found, or -1 if none exists. @param {*} searchElement: searchElement * @param {Number} fromIndex: start index * @returns {Number} index: return index of a given element */
// 1. Normal parameters
const arr1 = [2.3.4.6.5.6];
const index1 = arr1.lastIndexOf(6);
console.log(index1); / / 5
const index2 = arr1.lastIndexOf(3.2);
console.log(index2); / / 1
Copy the code

Array.prototype.map

/** * @author: const arr = array.prototype. Map ([item[,index[, Array]]])[, thisArg]) * @description: /** * @author: const arr = array.prototype. Map ([item[,index[, Array]]]) Creates a new array, the result of which is returned when each element in the array calls one of the provided functions. * @param {Function} callback: callback([item[,index[,array]]]) * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {Array} arr: returns an Array of primitives. * /
ThisArg cannot be bound to arrow function
const arr1 = [2.3.4];
const thisArg = { name: 'Thor' };
const ret1 = arr1.map((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return item * 2;
}, thisArg);
console.log('Operation value', ret1); // [4, 6, 8]
ThisArg = thisArg; thisArg = thisArg
const ret2 = arr1.map(function _every(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
    return item * 2;
}, thisArg);
console.log(ret2); // [4, 6, 8]

Copy the code

Array.prototype.pop

/** * @description: array.prototype.pop () removes the last element from the Array and returns the value of that element. This method changes the array length. * @returns {*} item: undefined * const item = array.prototype.pop () */
const arr = [1.2.3.4.5];
const item = arr.pop();
console.log(item); / / 5
console.log(arr); // [1, 2, 3, 4]

Copy the code

Array.prototype.push

/** * @description: array.prototype.push () adds one or more elements to the end of an Array and returns the Array's new length. * @returns {Number} length: new length of Array * const length = array.prototype. push(element1,... , elementN); * /
// 1, push an element
const arr = [1.2.3];
const length = arr.push(6);
console.log(length); / / 4
console.log(arr); // [1, 2, 3, 6]
// 2, push multiple elements
const arr1 = [1.2.3];
const length1 = arr1.push(5.7);
console.log(length1); / / 5
/ / 3, push (... arr)
const arr2 = [1.2.3];
const arr3 = [1.4.7];
constlength2 = arr2.push(... arr3);console.log(arr2); // [1, 2, 3, 1, 4, 7]
console.log(length2); / / 6

Copy the code

Array.prototype.reduce

/** * @author: Const ret = array.prototype. Reduce (Callback (Accumulator, currentValue[, index[, Array]])[, InitialValue] * @description: Perform the callback function (in ascending order) on each element in the array, summarizing the result into a single return value. * @param {Function} callback: Callback (Accumulator, currentValue[, index[, array]])[, InitialValue]) * @param {*} accumulator * @param {*} accumulator * @param {*} Accumulator Optional * @param {Array} Array: Array instance of the calling method. Optional. * @param {Number} initialValue:accumulator initialValue. Optional. * @returns {*} ret: This function is accumulator */
// 1
const arr1 = [2.3.4];
const arg = 10;
const ret1 = arr1.reduce((acc, item, index, arr) = > {
    // The value of the first operation is 10, the element of the operation is 2, the index of the element of the operation is 0, and the array of methods is 2,3,4
    console.log('Cumulative value:${acc}, operation elements:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return acc + item;
}, arg);
console.log(ret1);
// 2. Count the occurrences of each element
const arr2 = [2.3.4.1.2.3.3.4.4.4];
const arg2 = {};
const ret2 = arr2.reduce((acc, item, index, arr) = > {
    // The value of the first operation is 10, the element of the operation is 2, the index of the element of the operation is 0, and the array of methods is 2,3,4
    console.log('Cumulative value:${acc}, operation elements:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    if (item in acc) {
        acc[item] += 1;
    } else {
        acc[item] = 1;
    }
    return acc;
}, arg2);
console.log(ret2); // {'1': 1, '2': 2, '3': 3, '4': 4}
// 3. Categorize by attribute
const arr3 = [{ name: 'Alice'.age: 21 }, { name: 'Max'.age: 20 }, { name: 'Jane'.age: 20 }];
function groupBy(objectArray, property) {
    return objectArray.reduce((acc, obj) = > {
        const key = obj[property];
        if(! acc[key]) { acc[key] = []; } acc[key].push(obj);return acc;
    }, {});
}
const ret3 = groupBy(arr3, 'age');
console.log(ret3);
// { '20': [ { name: 'Max', age: 20 }, { name: 'Jane', age: 20 } ],
// '21': [ { name: 'Alice', age: 21 } ] }

Copy the code

Array.prototype.reverse

/** * @description: array.prototype. reverse reverses the position of the elements in the Array and returns the Array. This method changes the original array. Returns: {Array} arr: calls the Array instance of the original method. * const arr = Array.prototype.reverse(); * /
/ / 1, the reverse
const arr = [1.3.2.5.4];
const ret = arr.reverse();
console.log(arr); // [4, 5, 2, 3, 1]
console.log(ret); // [4, 5, 2, 3, 1]
console.log(ret === arr); // true

Copy the code

Array.prototype.shift

/** * @description: array.prototype. shift removes the first element from the Array and returns the value of that element. This method changes the length of the array. * @returns: {*} item: the first element in the array. Returns undefined if the array is empty. * const item = Array.prototype.shift(); * /
/ / 1, the shift
const arr = [1.3.2.5.4];
const ret = arr.shift();
console.log(arr); // [3, 2, 5, 4]
console.log(ret); / / 1

Copy the code

Array.prototype.slice

/** * @author: const arr= array.prototype. Slice ([begin[,end]]); * @description: shallow copy the array from the start index to the end index, return the new array. * @param {Number} begin: specifies the start index * @param {Number} end: specifies the end index * @returns {Array} arr: specifies the new Array for shallow copy */
// 1. Normal parameters
const arr1 = [2.3.4.5.6];
const ret1 = arr1.slice(2.4);
console.log(ret1); // [4, 5]
// 2
const arr2 = [2.3.4.5.6];
const ret2 = arr2.slice(4 -.- 1);
console.log(ret2); // [3, 4, 5]
// 3. Verify the shallow copy
const obj1 = { age: 'obj0' };
const obj2 = { name: 'obj2' };
const obj3 = { gender: 'obj2' };
const arr3 = [obj1, obj2, obj3];
const ret3 = arr3.slice(1.2);
console.log(ret3); // [ { name: 'obj1' } ]
ret3[0].name = 'change';
console.log(ret3); // [ { name: '修改' } ]
console.log(obj2); // [ { name: '修改' } ]

Copy the code

Array.prototype.some

/** * @author: const obj = array.prototype. Some ([item[,index[, Array]]])[, thisArg]) * @description: At least one element can pass the provided function method. This method returns a Boolean value. * @param {Function} callback: callback Function * @param {*} item: element being processed. * @param {Number} index: index of the element being processed. Optional. * @param {Array} Array: Array instance of the call method. Optional. * @param {Object} thisArg: Optional. Used as the value of this (reference object) when the callback function is executed. * @returns {undefined} obj: undefined */
// 1. Normal argument, arrow function cannot bind this
const arr1 = [2.3];
const thisArg = { name: 'Thor' };
const ret1 = arr1.some((item, index, arr) = > {
    console.log('this:'.this); / / {}
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`);
    return item > 2;
}, thisArg);
console.log('Operation value', ret1); // true
// 2. Normal argument, normal function binding this
const arr2 = [2.3];
const ret2 = arr2.some(function _every(item, index, arr) {
    console.log('this:'.this); // { name: 'Thor' }
    console.log('Operation element:${item}To operate on the index of an element:${index}, calling an array of methods:${arr}`); // operate element: 3, operate element index: 1, call method array: 2,3
    return item > 2;
}, thisArg);
console.log(ret2); // true

Copy the code

Array.prototype.sort

/* eslint-disable eqeqeq */
/** * @description: array.prototype.sort Sort Array elements by default. * @param: {Function} compareFunction specifies functions in a certain order. * compareFunction(firstEl,secondEl) firstEl: the first element used for comparison. SecondEl The second element used for comparison. Returns: {*} arr calls an instance of an array of methods. * const arr = Array.prototype.sort([compareFunction]); * /
// 1, sort(), which defaults to the ascending order of the string's Unicode code points
const arr = ['b'.1.'c'.3.2.'a'.5.4];
const ret = arr.sort();
console.log(arr); // [ 1, 2, 3, 4, 5, 'a', 'b', 'c' ]
console.log(ret); // [ 1, 2, 3, 4, 5, 'a', 'b', 'c' ]
console.log(ret === arr); // true
// 2. Sort (a,b)=>a-b); sort(a,b)=>a-b);
const arr2 = [{ name: 'c' }, { name: '2' }, { name: 'a' }, { name: '2' }, { name: '3' }, { name: 'b' }];
arr2.sort((a, b) = > {
    const A = a.name.toUpperCase();
    const B = b.name.toUpperCase();
    if (A < B) {
        return - 1;
    }
    if (A > B) {
        return 1;
    }
    return 0;
});
console.log(arr2); // [ { name: '2' }, { name: '2' }, { name: '3' }, { name: 'a' }, { name: 'b' }, { name: 'c' } ]
// 3, string and number sort, element conversion string, ASCII sort
const arr3 = ['1'.'b'.1.'c'.3.2.'a'.5.'张'];
arr3.sort();
console.log(arr3); // [1, '1', 2, 3, 5, 'a', 'b', 'c', 'zhang']
Copy the code

Array.prototype.splice

/* eslint-disable eqeqeq */
/** * @description: array.prototype.splice /** * @author: array.prototype.splice /** * @author: array.prototype.splice * And returns the modified contents as an array. This method changes the original array. * @param: {Number} start specifies the change position index +1. Start is greater than the array length, no operation. Negative numbers start in the last digit. * @param: {Number} deleteCount Optional, delete several elements. Delete all files after start by default. * @param: {*} item1,item2 optional, the element to be added to the array, starting at the start position. If not specified, splice() will delete only array elements. * @returns: {Array} arr An Array of deleted elements. Const arr = array.prototype. Splice (start[, deleteCount[, Item1 [, item2[,...]]]]); * /
// 1, pass only one parameter start
const arr = [1.2.3.4.5];
const retArr = arr.splice(1);
console.log(arr === retArr);
console.log(arr); / / [1]
console.log(retArr); // [2, 3, 4, 5]
// 1-1, pass negative number start
const arrA = [1.2.3.4];
const retArrA = arrA.splice(- 1);
console.log(arrA); // [1, 2, 3]
console.log(retArrA); / / [4]
// 2, start is greater than the array length, does not change the original array
const arr1 = [1.2.3];
const retArr1 = arr1.splice(4);
console.log(arr1); // [1, 2, 3]
console.log(retArr1); / / []
// 3. Start deleteCount
const arr2 = [1.2.3.4.5];
const retArr2 = arr2.splice(2.2);
console.log(arr2); // [1, 2, 5]
console.log(retArr2); // [3, 4]
// 3. If start is passed,deleteCount is greater than the number of elements after start
const arr3 = [1.2.3.4.5];
const retArr3 = arr3.splice(2.10);
console.log(arr3); // [1, 2]
console.log(retArr3); // [3, 4, 5]
// all parameters are passed in. The added element is more than the deleted element
const arr4 = [1.2.3.4];
const retArr4 = arr4.splice(2.5. [5.6.7.8]);
// const retArr4 = arr4.splice(2, 5, 5, 6, 7, 8);
console.log(arr4); // [1, 2, 5, 6, 7, 8]
console.log(retArr4); // [3, 4]

Copy the code

Array.prototype.unshift

/** * @description: array.prototype. Unshift Adds one or more elements to the beginning of an Array. Returns the array length * @param: {*} item: one or more elements added to the array * @returns: Const length = array.prototype. Unshift (element1,... , elementN); * /
// 1.unshift
const arr = [3.4.5];
const ret = arr.unshift(1.2);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(ret); / / 5
// 2. Add multiple elements
const arr1 = [4.5.6];
constret1 = arr1.unshift(... [1.2.3]);
console.log(arr1); // [1, 2, 3, 4, 5, 6]
console.log(ret1); / / 6

Copy the code

Array.prototype.values

/* eslint-disable no-restricted-syntax */
* @author: const iterator = array.prototype.values () * @description: const iterator = array.prototype.values () Returns an Array Iterator containing all the value keys in the Array. Returns {Iterator} Iterator: new Iterator object */
// 1. Normal parameters
const arr1 = [4.2.4.43];
const obj = arr1.values();
for (const value of obj) {
    console.log(value); // expected output: 4,2,43,2
}

Copy the code

Symbol

/* eslint-disable eqeqeq */
/** * @author: Symbol ES6 new base data type */
// 1.symbol () globally unique value, which is unique for each run
const symbol1 = Symbol(Fight Club);
const symbol10 = Symbol(Fight Club);
const symbol2 = Symbol('Memories of murder');
console.log(symbol1 === symbol10); // false
console.log(symbol1 == symbol10); // false
console.log(typeof symbol2); // symbol
// 2.Symbol.for(); Global search, if not found, do not create
const king1 = Symbol.for('The King's Speech');
const king2 = Symbol.for('The King's Speech');
console.log(king1 === king2); // true
// 3.Sym.keyFor(symbol); Returns the description of a Symbol
console.log(Symbol.keyFor(king1)); The King's Speech

Copy the code

Symbol.match

Symbol.replace

Symbol.search

Symbol.split

Symbol.hasInstance

/* eslint-disable func-names */
// Symbol.match;
// Symbol.replace;
// Symbol.search;
// Symbol.split;
// Symbol.hasInstance
// 1.function
const SymbolFunc = function _symbolFunc(name) {
    this.name = name;
    this[Symbol.match] = function (foo) {
        return this.name.match(foo);
    };
};
SymbolFunc.prototype[Symbol.match] = function (foo) {
    return this.name.match(foo);
};
SymbolFunc.prototype[Symbol.hasInstance] = function (foo) {
    return this.name.match(foo);
};
const symbol = new SymbolFunc('will');
console.log(', '.match(symbol)); // [' id ', index: 1, INPUT: 'ID']
// 2.class
class SymbolClass {
    constructor(name) {
        this.name = name;
    }

    // foo instanceOf symbolClass
    [Symbol.hasInstance](foo) {
        return this.name === foo;
    }

    // foo.match(symbolClass)
    [Symbol.match](foo) {
        return this.name.match(foo);
    }

    // foo.replace(symbolClass)
    [Symbol.replace](foo) {
        this.name.replace('a', foo);
    }

    // foo.search(symbolClass)
    [Symbol.search](foo) {
        return this.name.search(foo);
    }

    // foo.split(symbolClass)
    [Symbol.split](foo) {
        this.foo.split(foo); }}const symbol1 = new SymbolClass('Zhang Panqin');
console.log('张'.match(symbol1)); // [' zhang ', index: 0, input: 'Zhang Panqin']

Copy the code

Function

// 1. Function default arguments
const func = function _func(name = 'default') {
    console.log(name);
};
func(); / / the default
func(Artificial intelligence); // Artificial intelligence
// 2. Function parameter structure assignment
const func2 = function _func2({ name = 'Harry Potter', age = 18 }) {
    console.log(`${name}-${age}`);
};
func2({ name: 'harry' }); // Harry Potter -18
func2({ name: 'will'.age: 'the' }); // will-19
// 3. Tail Call, where the last step of a function calls another function, to avoid bursting the stack. Examples of ruan Yifeng ES6 entry
const Fibonacci = function _Fibonacci(n) {
    if (n <= 1) {
        return 1;
    }
    return _Fibonacci(n - 1) + _Fibonacci(n - 2);
};
// Code optimized for tail-recursive calls
const Fibonacci2 = function _Fibonacci2(n, ac1 = 1, ac2 = 1) {
    if (n <= 1) {
        return ac2;
    }

    return _Fibonacci2(n - 1, ac2, ac1 + ac2);
};
console.log(Fibonacci2(100)); / / 573147844013817200000
// Time out, stack burst
console.log(Fibonacci(100));

Copy the code

Function.prototype.apply

/** * @author: Apply (thisArg, [argsArray]) * @description: Calls a Function with the given this value and the arguments provided as an array (or array-like object). * @param {Object} thisArg function run binding this Object * @param {Array} argsArray passed to the function argument */
// Not an arrow function
const game = 'Breath of zelda's Wild';
global.name = 'link';
const playGame = function _playGame(gameName) {
    console.log(`The ${this.name}${gameName}`);
};
playGame(game); // Link plays Breath of zelda's Wild
playGame.apply({ name: 'Zhang Panqin' }, [game]); // Zhang Panqin plays Breath of zelda's Wild
// Arrow function cannot bind this
const sleep = (a)= > {
    console.log(this); / / {}
    console.log(`The ${this.name}Sleep `);
};
sleep(); / / undefined to sleep
sleep.apply({ name: 'link' }); / / undefined to sleep

Copy the code

Function.prototype.call

/** * @author: Function. Prototype. Call (thisArg,[, arg1[, arg2[, ...]]]) * @description: call a function with the given value of this * @param {Object} thisArg function runtime binding this * @param {*} arg1 passed to the function argument */
// Not an arrow function
const game = 'Breath of zelda's Wild';
global.name = 'link';
const playGame = function _playGame(gameName) {
    console.log(`The ${this.name}${gameName}`);
};
playGame(game); // Link plays Breath of zelda's Wild
playGame.call({ name: 'Zhang Panqin' }, game); // Zhang Panqin plays Breath of zelda's Wild
// Arrow function cannot bind this
const sleep = (a)= > {
    console.log(this); / / {}
    console.log(`The ${this.name}Sleep `);
};
sleep(); / / undefined to sleep
sleep.call({ name: 'link' }); / / undefined to sleep

Copy the code

Function.prototype.call

/** * @author: Const func= function.prototype. Call (thisArg,[, arg1[, arg2[,...]]]) * @description: Create a new Function and set this keyword to the supplied value when called. * @param {Object} thisArg * @param {*} arg1 returns a copy of the original Function. And takes the specified this value and initial arguments. * /
// Not an arrow function
const game = 'Breath of zelda's Wild';
global.name = 'link';
const playGame = function _playGame(gameName) {
    console.log(`The ${this.name}${gameName}`);
};
playGame(game); // Link plays Breath of zelda's Wild
const exec1 = playGame.bind({ name: 'Zhang Panqin' }, game);
exec1(); // Zhang Panqin plays Breath of zelda's Wild
// Arrow function cannot bind this
const sleep = (a)= > {
    console.log(this); / / {}
    console.log(`The ${this.name}Sleep `);
};
sleep(); / / undefined to sleep
const exec2 = sleep.bind({ name: 'link' });
exec2(); / / undefined to sleep

Copy the code

Object

Object.assign

/** * @author: const obj= object.assign (target,... Sources * @description is used to copy the values of all enumerable properties from one or more source objects to the target object. * The source object property overrides the same property of the target object, which returns the target object. * @param target Target object * @param Sources source object * @returns obj Target object obj===target true */
// 1. Copy objects
const obj = { a: 1 };
const target1 = { a: 2.b: 2 };
const copy = Object.assign(target1, obj);
console.log(copy === target1); // true
console.log(copy); // { a: 1, b: 2 }

// 1.2 Extension operators for copy objects...
consttarget2 = { ... target1, ... obj };console.log(target2); // { a: 1, b: 2 }
// 2. Inherited attributes and non-enumerable attributes cannot be copied
const prototype = Object.create(
    { extend: 22 },
    {
        bar: {
            value: 'bar'.// bar is a non-enumerable property
        },
        baz: {
            value: 'baz'.enumerable: true.// baz is a self-enumerable property}},);// prototype {baz: "baz", bar: "bar"} extend is a property on the prototype object
const target3 = { a: 3 };
Object.assign(target3, prototype);
console.log(target3); // { a: 3, baz: 'baz' }

// copy based on class
class Parent {
    constructor(name) {
        this.name = name;
    }

    getName() {
        return this.name; }}class Son extends Parent {
    constructor(age, name) {
        super(name);
        this.age = age;
    }

    getAge() {
        return this.age; }}const son = new Son('age'.'name');
const ret = Object.assign({ gender: 'male' }, son);
console.log(ret); // {gender: 'male ', name: 'name', age: 'age'}

// 4, copy the properties of Symbol type
const o1 = { a: 1 };
const o2 = { [Symbol('foo')]: 2 };
const retObj = Object.assign({}, o1, o2);
console.log(retObj); // { a: 1, [Symbol(foo)]: 2 }

Copy the code

Object.create

/* eslint-disable no-proto */
/** * @author: create a new object with the specified prototype object and properties. * const ret=Object.create(proto, Ret.__proto__ is proto * @param proto: The prototype object of the newly created object. @param propertiesObject: Optional. * @returns RET A new object with the specified prototype object and properties */
// 1. Simple requirements
const prototype = { age: 'age'.name: 'name' };
const newObject = Object.create(prototype, {
    sex: {
        value: 'sex'.enumerable: true.// Whether it can be enumerated
    },
    hobby: {
        value: 'hobby'.enumerable: true.// Whether it can be enumerated}});console.log(newObject); // { sex: 'sex', hobby: 'hobby' }
console.log(newObject.__proto__ === prototype); // true

const Parent = function aa(name) {
    this.name = name;
    this.getName = function _getName() {
        console.log('getName');
        return this.name;
    };
};
Parent.prototype.move = function _move() {
    console.log('move');
};

const Son = function son(age, name) {
    Parent.call(this, name);
    this.age = age;
    this.getAge = function _getAge() {
        return this.age;
    };
};
Son.prototype = Object.create(Parent.prototype);
console.log(Son.prototype === Parent.prototype); // false
console.log(Son.prototype.__proto__ === Parent.prototype); // true
debugger;
console.log(Son);

Copy the code

Object.defineProperties

/** * @Author: Const ret = object.defineProperties (obj, props) * const ret = object.defineProperty (obj, prop, props) Descriptor) // Add a property or modify an existing property description and return the object obj * @description Add a new property or modify an existing property and property description on an object and return the object obj * @param obj: object to be operated on. * @param props: Property description * @returns ret A new object, with the specified prototype object and properties */
// 1. Simple requirements
const prototype = { age: 'age'.name: 'name' };
const newObject = Object.defineProperties(prototype, {
    sex: {
        value: 'sex'.// Attribute value, default undefined
        enumerable: true.// Whether it can be enumerated
        configurable: true.// The default is false. A value of true indicates that the sex property can be deleted and the property descriptor can be changed
        writable: true.// The default is false. A value of true indicates that value can be changed by the assignment operator
    },
    hobby: {
        value: 'hobby'.enumerable: false.// Whether it can be enumerated
        configurable: false.// The default is false. True means that the Hobby property can be removed and the property descriptor can be changed
        writable: false.// The default is false. A value of true indicates that value can be changed by the assignment operator
    },
    test: {
        value: 'test'.configurable: true,}});// The Hobby property descriptor enumerable is false, which means that the object property cannot be enumerable but can be retrieved
console.log(newObject); // { age: 'age', name: 'name', sex: 'sex' }
console.log(newObject.hobby); // hobby
// The hobby property descriptor is true, which indicates that the hobby property cannot be modified
newObject.hobby = 'hobby modified';
console.log(newObject.hobby); // hobby
// Signals: true, indicates that the property can be deleted
delete newObject.hobby;
delete newObject.sex;
console.log(newObject.hobby); // hobby
console.log(newObject.sex); // undefined
// test cannot be modified
prototype.test = '11';
console.log(prototype.test);
Object.defineProperties(prototype, {
    test: {
        value: 'test11'.enumerable: true.configurable: true.writable: true,}});console.log(prototype); // { age: 'age', name: 'name', test: 'test11' }
// test cannot be modified
prototype.test = '11';
console.log(prototype.test); / / 11

Copy the code

Object.entries

/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/** * @author: const arr = object. entries(obj) * @description Returns an array of key-value pairs for a given Object's own enumerable properties, arranged in the same way as for... The in loop returns the same order as it iterates through the object (the difference is that for-In loops also enumerate properties in the prototype chain). * @param {Object} obj: the Object to operate on. * @returns {Array} arr */
/ / 1.
const obj = { name: 'name'.age: 11 };
const arr = Object.entries(obj);
console.log(arr); // [ [ 'name', 'name' ], [ 'age', 11 ] ]
for (const [key, value] of arr) {
    console.log('key', key);
    console.log('value', value);
}
// 2. Enumerate properties that the object itself can enumerate
const parent = { name: 'IronMan'.age: 18 };
const obj2 = Object.create(parent, {
    hobby: {
        value: 'I love you three thousand times'.enumerable: false.// Attributes are not enumerable
    },
    test: {
        value: 'test'.enumerable: true,}});console.log('Integrate name and age properties from Prototype', obj2.name); // IronMan
console.log('Integrate name and age properties from Prototype', obj2.age); / / 18
console.log('Non-enumerable properties, Hobby', obj2.hobby); // I love you three thousand times
// Only enumerable attributes of the object can be traversed
const arr2 = Object.entries(obj2);
for (const [key, value] of arr2) {
    console.log('key,value=>'.`${key}.${value}`); // key,value test,test
}
// forin // traverses enumerable properties on itself and the stereotype
for (const key in obj2) {
    // Attribute key-- value value test--test
    // Attribute key-- value value name--IronMan
    // Attribute key-- value value age--18
    console.log('Attribute key-- value value'.`${key}--${obj2[key]}`);
}

Copy the code

Object.freeze

/* eslint-disable no-proto */
/** * @author: Const ret1 = object.freeze (obj) * @description Freeze an Object. * Attributes cannot be added, modified, or deleted from obj; Property descriptors cannot be modified either. Because it is shallow frozen, the properties of the prototype object can be modified. * @param {Object} obj: Object to be frozen. * @returns {Object} Object for ret1 operation. Obj = = = ret1 to true * /
/ / 1.
const parent = { name: 'IronMan'.age: 18.testObj: { test: 'test'}};const obj2 = Object.create(parent);
obj2.data = { hobby: 'Go to the movies' };
obj2.gender = 'male';
// Freeze obj2 before you modify the stereotype properties
console.log('name attribute', obj2.name); // IronMan
obj2.__proto__.name = 'Iron Man';
console.log('name attribute', obj2.name); / / iron man
obj2.__proto__.name = 'IronMan';
console.log('name attribute', obj2.name); // IronMan
// Freeze the object
const ret = Object.freeze(obj2);
console.log(ret === obj2); // true
console.log('Frozen obj2', obj2); // {data: {hobby: 'watch a movie '}, gender:' male '}
// Verify that the prototype can be modified, and conclude that attributes can be added, deleted, and updated in the prototype object
console.log('name attribute', obj2.name); // IronMan
obj2.__proto__.name = 'Iron Man';
console.log('name attribute', obj2.name); / / iron man
console.log('name attribute', obj2.__proto__.name); / / iron man
delete obj2.__proto__;
console.log('delete obj2.__proto__', obj2.__proto__); // {name: 'Iron Man ', age: 18, testObj: {test: 'test'}}
obj2.__proto__.add = 'add';
console.log('obj2.__proto__. Add Add attributes', obj2.__proto__.add); // add

// Modify its own basic data type, after freezing cannot add attributes
obj2.hobby = 'Watch the movie, Avengers 4';
console.log(obj2); // {data: {hobby: 'watch a movie'}, gender: 'male'}
// Attributes cannot be deleted after freezing
delete obj2.data;
console.log(obj2); // {data: {hobby: 'watch a movie'}, gender: 'male'}
// Attributes cannot be modified after freezing
obj2.gender = 'nan';
console.log(obj2); // {data: {hobby: 'watch a movie'}, gender: 'male'}
// Modify its own object
obj2.data.hobby = 'Watch the Movie, the Matrix.';
console.log(obj2); // {data: {hobby: 'Watch movies, the Matrix '}, gender:' male '}

// Deep freeze implementation
Object.deepFreeze = function deepFreeze(obj) {
    // Get the property name defined on obj
    const propNames = Object.getOwnPropertyNames(obj);

    // Freeze attributes before freezing themselves
    propNames.forEach((name) = > {
        const prop = obj[name];
        // If prop is an object, freeze it
        if (typeof prop === 'object'&& prop ! = =null) { deepFreeze(prop); }});// Freeze yourself (no-op if already frozen)
    return Object.freeze(obj);
};

console.log('Before deep freeze', obj2); // {data: {hobby: 'Watch movies, the Matrix'}, gender: 'male'}
Object.deepFreeze(obj2);
obj2.data.hobby = 'Watch the movie, Forrest Gump';
// Deep freeze succeeded
console.log(obj2); // {data: {hobby: 'Watch movies, the Matrix '}, gender:' male '}

Copy the code

Object.getOwnPropertyDescriptor

/ * * * @ Author: zhang qin * const climbing ret = Object. GetOwnPropertyDescriptor (obj, prop) * @ the description to return on the specified Object corresponding to the attribute descriptor. Cannot return on the prototype object. * @param {Object} obj: the Object to operate on. * @param {String} prop: object property. * @returns {Object} ret Object property operator */
const parent = { age: 18 };
const obj = Object.create(parent);
obj.name = 'Thanos';

// 1. Get the object's own property operator
const ret = Object.getOwnPropertyDescriptor(obj, 'name');
console.log('Object property operator', ret); // { value: 'Thanos', writable: true, enumerable: true, configurable: true }

// 2. Get a property on the prototype object
const ret2 = Object.getOwnPropertyDescriptor(obj, 'age');
console.log('Stereotype object own property operator', ret2); // undefined

Copy the code

Object.getOwnPropertyNames

/ * * * @ Author: zhang qin * const climbing arr = Object. GetOwnPropertyNames (obj) * @ the description to return to the array Object itself attribute names. Both non-enumerable and enumerable are returned. * @param {Object} obj: the Object to operate on. * @returns {Array} All attributes of the ARR object. * /
const parent = { name: 'Captain America'.age: 100 };
const obj = Object.create(parent, {
    hobby: {
        value: 'I missed an appointment! '.enumerable: false.// false, the property is not enumerable}}); obj.gender ='male';
console.log('Get the name attribute from the prototype object parent :', obj.name); // Captain America
console.log(obj); // {gender: 'male'}
const arr = Object.getOwnPropertyNames(obj);
console.log(arr); // [ 'hobby', 'gender' ]

Copy the code

Object.getOwnPropertySymbols

/** * @Author: Zhang qin * const climbing arr = Object. GetOwnPropertySymbols (obj) * @ description returns an Object's own * @ Symbol attribute param {Object} obj: Object need to freeze. * @returns {Array} arr: Array of Symbol properties. * /
const Natasha = Symbol('Natasha');
const beauty = Symbol('beauty');
const age = Symbol('age');
const parent = { [age]: 18.height: 170 };
console.log(parent); // { height: 170, [Symbol(age)]: 18 }
const obj = Object.create(parent);
obj[Natasha] = 'Natasha';
obj[beauty] = 'beauty';
obj.gender = 'woman';
console.log(obj); / / {gender: 'female' and [Symbol (Natasha)] : 'Natasha, [Symbol (beauty)] :' beauty '}
const arr = Object.getOwnPropertySymbols(obj);
// Return only the Symbol attribute of itself
console.log(arr); // [ Symbol(Natasha), Symbol(beauty) ]

Copy the code

Object.getPrototypeOf

/* eslint-disable new-cap */
/* eslint-disable no-unused-expressions */
/* eslint-disable symbol-description */
/* eslint-disable no-proto */
/** * @Author: Const ret= object.getProtoTypeof (obj) * @description method returns the prototype Object of the specified Object ret===obj.__proto__ is true * @param {Object} Obj: object to operate on. * @returns {Object} ret: the prototype Object of the operation Object */
// 1.Object.create()
const parent = { name: 'Hulk'.age: 18 };
// object.create (parent) adds parent to the return Object __proto__
const obj = Object.create(parent);
obj.prototype = { height: 178.description: 'Perfect height, same as me, ha ha! ' };
console.log(obj.prototype === parent); // false
console.log(obj.__proto__ === parent); // false
const ret = Object.getPrototypeOf(obj);
console.log(ret); // { name: 'Hulk', age: 18 }
// 2. Copy __proto__ directly to the object
const obj2 = { weight: '58kg'.description: 'There's something wrong with the numbers. You're in average shape.' };
const prototype2 = { [Symbol()] :'test' };
obj2.prototype = prototype2;
const ret2 = Object.getPrototypeOf(obj2);
console.log(ret2); / / {}
obj2.__proto__ = prototype2;
const ret3 = Object.getPrototypeOf(obj2);
console.log(ret3); // { [Symbol()]: '测试' }
console.log(ret3 === prototype2); // true
/ / 3. The Function
const getName = function _getName() {
    return 'Hulk';
};
const getAge = function _getAge() {
    return 18;
};
getAge.prototype = getName;
const ret4 = Object.getPrototypeOf(getAge);
console.log(ret4 === Object.__proto__); // true
const obj4 = new getAge();
const ret5 = Object.getPrototypeOf(obj4);
ret5 === obj4.__proto__;
console.log(ret5 === obj4.__proto__); // true
// 4. class
class A {}
class B extends A {}
const ret6 = Object.getPrototypeOf(B);
console.log(B.__proto__ === A); // true
console.log(B.__proto__ === ret6); // true
const b = new B();
const ret7 = Object.getPrototypeOf(b);
console.log(b.__proto__ === ret7); // true

Copy the code

Object.is

/** * @Author: Const bool = object. is(obj1,obj2), const bool = object. is(obj1,obj2), const bool = Object. Obj1: the object to operate on. * @param {*} obj2: the object to operate on. * @RETURNS {Boolean} bool: Whether the two parameters are equal */

// Both values are null
// Both values are true or false
// Two values are strings of the same number of characters in the same order
// Both values point to the same object
// Both values are numbers and
// Both are positive 0 +0
// Both are negative zero -0
/ / is NaN
// all numbers are the same except zero and NaN
// 1. Compare two values are the same as undefined
console.log(Object.is(undefined.undefined)); // true
console.log(Object.is(null.null)); // true
console.log(Object.is(true.true)); // true
console.log(Object.is(false.false)); // true
console.log(Object.is(NaN.NaN)); // true
console.log(Object.is('a'.'a')); // true
console.log(Object.is('a'.'a')); // true
// 2
console.log(Object.is('1'.1)); // false
console.log(Object.is(+0.0)); // false
console.log(Object.is(0.0)); // false
console.log(Object.is(0, +0)); // true
// 3
const obj = { age: 1 };
const obj2 = { age: 1 };
console.log(Object.is(obj, obj2)); // false

Copy the code

Object.isFrozen

/** * @Author: Const bool = object.isfrozen (obj) * @description whether the Object isFrozen, object.freeze (obj) must be frozen Object * @param {Object} obj1: The object to operate on. * @RETURNS {Boolean} bool: Indicates whether the object is frozen. * /
/ / 1, the Object. IsFrozen
const obj = { age: 1 };
Object.freeze(obj);
console.log(Object.isFrozen(obj)); // true
// A frozen object is also a sealed object.
console.log(Object.isSealed(obj)); // true
// Of course, it is an unextensible object.
console.log(Object.isExtensible(obj)); // false
/ / 2.
const obj2 = { release: 'the kraken! ' };
Object.defineProperty(obj2, 'release', { writable: false });
console.log(Object.isFrozen(obj2)); // false
// A frozen object is also a sealed object.
console.log(Object.isSealed(obj2)); // false
// Of course, it is an unextensible object.
console.log(Object.isExtensible(obj2)); // true
/ / 3.
const obj3 = { release: 'the kraken! ' };
Object.defineProperty(obj3, 'release', { configurable: false });
console.log(Object.isFrozen(obj3)); // false
// A frozen object is also a sealed object.
console.log(Object.isSealed(obj3)); // false
// Of course, it is an unextensible object.
console.log(Object.isExtensible(obj3)); // true

Copy the code

Object.keys

/** * @Author: * const arr = object.keys (obj) * @description Enumerates the attributes of an Object that implements the iterative interface. Symbol * @param {Object} obj: objects to operate on. Returns {*} arr: iterator key */
// 1. String
const str = '1234556';
console.log(Object.keys(str)); // ['0', '1', '2', '3', '4', '5', '6']
/ / 2. The array
const arr = [1.2.3];
console.log(Object.keys(arr)); // ['0', '1', '2']
/ / 3. The object
const parent = { name: 'IronMan'.age: 18 };
const obj = Object.create(parent, {
    hobby: {
        value: 'I love you three thousand times'.enumerable: false.// Attributes are not enumerable
    },
    test: {
        value: 'test'.enumerable: true,}});// The Hobby property cannot be enumerated
console.log(obj.hobby); // 'I love you three thousand times'
// Only attributes that can be enumerated by themselves can be obtained
console.log(Object.keys(obj)); // [ 'test' ]

Copy the code

Object.preventExtensions

/** * @Author: Const obj1 = object.preventExtensions (obj) * @description Prevents the Object from extending its own properties * @param {Object} obj: The object to operate on. * @returns {Object} obj1: obj===obj1 is true */
/ / 1.
const obj = { name: 'name' };
const ret = Object.preventExtensions(obj);
console.log(obj === ret); // ret
// You can modify the original attributes
obj.name = 1;
console.log(obj);
// Attributes cannot be added
obj.age = 1;
console.log(obj);
// You can delete attributes
delete obj.name;
console.log(obj); / / {}

Copy the code

Object.setPrototypeOf

/* eslint-disable no-proto */
/** * @Author: Const ret= object.setPrototypeof (obj, __proto__) * @description Sets the Object's prototype Object obj.__proto__ === __proto__ to true. ES6 formally recommended method for setting prototype objects. * @param {Object} obj: the Object to operate on. * @param {Object} __proto__: obj prototype Object. * @returns {Object} ret ret===obj is true */
// 1.Object.create()
const parent = { name: 'Hulk'.age: 18 };
const son = {};
const obj = Object.setPrototypeOf(son, parent);
obj.prototype = { height: 178.description: 'Perfect height, same as me, ha ha! ' };
console.log(son === obj); // true
console.log(son.prototype === parent); // false
console.log(son.prototype.__proto__ === parent); // false
console.log(son.__proto__ === parent); // true
const ret = Object.getPrototypeOf(obj);
console.log(ret); // { name: 'Hulk', age: 18 }
// 2
const getName = function _getName() {
    return 'Hulk';
};
const getAge = function _getAge() {
    return 18;
};
Object.setPrototypeOf(getAge, getName);
const ret4 = Object.getPrototypeOf(getAge);
console.log(getAge.__proto__ === getName); // true
console.log(getAge.__proto__ === ret4); // true
console.log(getName === ret4); // true
// 4. class
class A {}
class B {}
Object.setPrototypeOf(B, A);
const ret6 = Object.getPrototypeOf(B);
console.log(B.__proto__ === A); // true
console.log(B.__proto__ === ret6); // true
const b = new B();
const ret7 = Object.getPrototypeOf(b);
console.log(b.__proto__ === ret7); // true

Copy the code

Object.values

/** * @Author: Const arr = object. values(obj) * @description Enumerates the values of the attributes of an Object that can be enumerated by itself. The object to operate on. Returns {*} arr: iterators can enumerate the values of attributes */
// 1. String
const str = '23456';
console.log(Object.values(str)); // ['2', '3', '4', '5', '6']
/ / 2. The array
const arr = [1.2.3];
console.log(Object.values(arr)); // ['0', '1', '2']
/ / 3. The object
const parent = { name: 'IronMan'.age: 18 };
const obj = Object.create(parent, {
    hobby: {
        value: 'I love you three thousand times'.enumerable: false.// Attributes are not enumerable
    },
    test: {
        value: 'test'.enumerable: true,}});// The Hobby property cannot be enumerated
console.log(obj.age); // 'I love you three thousand times''
console.log(Object.values(obj)); // [ 'test' ]

Copy the code

class

/** * @author: @description: Class can be seen as just a syntax candy, implementation is simpler than ES5. * Class constructor automatically adds an empty parameter to the constructor when it does not exist * and based on instanceof determining the type more accurately * all methods defined inside the class, It is defined in class.prototype and is non-enumerable. * /
// 1. Based on class
class A {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    getName() {
        return this.name;
    }

    getAge() {
        return this.age;
    }

    // Method defined in Prototype
    ['test'] () {return this.age; }}const a = new A('Miranda'.40);
console.log(a.getAge()); / / 40
console.log(a.getName()); / / loma Linda
console.log(A === A.prototype.constructor); // true
console.log(a instanceof A); // true
// Methods defined within a class are not enumerable
console.log(Object.keys(A.prototype)); / / []

// 2
const B = function _B(name, age) {
    this.name = name;
    this.age = age;
};
B.prototype = {
    constructor: B,
    getName() {
        return this.name;
    },
    getAge() {
        return this.age; }};const b = new B('Miranda'.40);
console.log(b.getAge()); / / 40
console.log(b.getName()); / / loma Linda
console.log(B === B.prototype.constructor); // true
console.log(b instanceof B); // true
// Different from class
console.log(Object.keys(B.prototype)); // [ 'constructor', 'getName', 'getAge' ]

Copy the code

Class static properties and methods

/** * @author: @description: Class can be seen as just a syntax candy, implementation is simpler than ES5. * Class constructor automatically adds an empty parameter to the constructor when it does not exist * and based on instanceof determining the type more accurately * all methods defined inside the class, It is defined in class.prototype and is non-enumerable. * /
// 1. Based on class
class A {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    getName() {
        return this.name;
    }

    getAge() {
        return this.age;
    }

    // Method defined in Prototype
    ['test'] () {return this.age; }}const a = new A('Miranda'.40);
console.log(a.getAge()); / / 40
console.log(a.getName()); / / loma Linda
console.log(A === A.prototype.constructor); // true
console.log(a instanceof A); // true
// Methods defined within a class are not enumerable
console.log(Object.keys(A.prototype)); / / []

// 2
const B = function _B(name, age) {
    this.name = name;
    this.age = age;
};
B.prototype = {
    constructor: B,
    getName() {
        return this.name;
    },
    getAge() {
        return this.age; }};const b = new B('Miranda'.40);
console.log(b.getAge()); / / 40
console.log(b.getName()); / / loma Linda
console.log(B === B.prototype.constructor); // true
console.log(b instanceof B); // true
// Different from class
console.log(Object.keys(B.prototype)); // [ 'constructor', 'getName', 'getAge' ]

Copy the code

The class inheritance

/* eslint-disable no-proto */
/** ** ** ** ** ** ** ** ** ** * Class A{} * class B extends A{} * B.__proto__===A is __proto__ === A. protoType is true, the subclass instance integrates the ordinary method of the parent class, the prototype of B is the prototype of A, the ordinary method defined on A is both the method on the prototype of A, So B integrates A's ordinary methods. * ES6 states that when a method of a parent class is called through super in a subclass normal method, this inside the method refers to the current subclass instance. * /
// 1. Based on class
class A {
    constructor(name) {
        this.name = name;
    }

    getName() {
        return this.name;
    }

    static staticGetName() {
        return this.staticName;
    }
}
A.staticName = O 'good';
class B extends A {
    constructor(name, age) {
        super(name);
        this.age = age; }}console.log(B.__proto__ === A); // true
console.log(Object.getPrototypeOf(B) === A); // true
console.log(B.prototype.__proto__ === A.prototype); // true
console.log(B.staticGetName());
console.log(B.staticName);

Copy the code

Proxy

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * Handler.get () intercepts the set property operation of an object. Object.create(proxy)[foo] * reflect.get () * * handler.set(); / / proxy[foo] = bar and proxy. Foo = bar *; / / proxy[foo] = bar *
// 1
const handler = {
    // Intercepts the constructor
    construct(target, argumentsList, targetConstructor) {
        console.log(targetConstructor);
        return newtarget(... argumentsList); },// Target is the proxied object, and name is the access attribute.
    get(target, name) {
        console.log('Before interception');
        return name in target ? target[name] : 37;
    },
    set(target, name, value) {
        // target proxied object
        // name The attribute to be accessed
        // The value of the target.name attribute
        if (name in target) {
            target[name] = value;
            return;
        }
        target[name] = 'Default value'; }};const Person = function _Person(name) {
    this.name = name;
};
const proxyPerson = new Proxy(Person, handler);
const obj = new proxyPerson('look crazy');
console.log(obj.name);
const p = new Person('broken jade');
console.log(p.name);

Copy the code

handler.apply

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * Handler.apply (), which returns any value. * This interceptor can intercept the following operations: * 1. Function.prototype.call() * 3, Reflect. Apply () */
// 1
const person = {
    name: 'No Cliff'./ / rest parameters
    getName() {
        return this.name; }};const handler = {
    ThisArg: the context object when called. * argumentsList: The array of arguments when called. * /
    apply(target, thisArg, argumentsList) {
        console.log(target === person.getName); // true
        console.log(thisArg); // undefined
        console.log(argumentsList); // [1, 2, 3]
        returntarget.bind(person, argumentsList)(); }};const proxy = new Proxy(person.getName, handler);
console.log(proxy(1.2.3)); / / no cliff
// 2. Bind the context of the function
const liangXiao = {
    name: 'liang xiao'./ / rest parameters
    getName() {
        return this.name; }};const handler2 = {
    ThisArg: the context object when called. * argumentsList: The array of arguments when called. * /
    apply(target, thisArg, argumentsList) {
        console.log(target === liangXiao.getName); // true
        console.log(thisArg); // getName: [Function: getName]}
        console.log(argumentsList); // [1, 2, 3]
        returntarget.apply(thisArg, argumentsList); }};const proxy2 = new Proxy(liangXiao.getName, handler2);
console.log(proxy2.call(liangXiao, 1.2.3)); / / liang xiao
console.log(proxy2.apply(liangXiao, [1.2.3])); / / liang xiao

Copy the code

handler.construct

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. Handler. Construct (), must return the object. * This interceptor can intercept the following operations: * 1. Args) * 2, reflect.construct () */
// 1
const Person = function _Person(name) {
    this.name = name;
};
const handler = {
    /** * Target: the proxy object's constructor * argumentsList: the argument to which the proxy object is called * targetConstructor: proxy object */
    construct(targetConstructor, argumentsList, proxy) {
        console.log(argumentsList); // [' feng ', 10]
        console.log(targetConstructor === Person); // true
        console.log(proxy); // proxyPerson
        return newtargetConstructor(... argumentsList); }};const proxyPerson = new Proxy(Person, handler);
const obj = new proxyPerson('look crazy'.10); // Execute constructor, intercepted
console.log(obj.name);
const p = new Person('broken jade'); // The execution constructor was not intercepted
console.log(p.name);

Copy the code

handler.defineProperty

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * Handler.defineProperty (), which must return Boolean indicating whether the operation was successful. * The interceptor can intercept the following operations: * 1, reflect.defineProperty () * 2, Object.defineProperty() */
// 1
const person = { name: 'No Cliff' };
const handler = {
    /** * target: propped object * prop: Property name to be modified * Descriptor: property descriptor */
    defineProperty(target, prop, descriptor) {
        console.log(target === person); // true
        return Object.defineProperty(target, prop, descriptor); }};const descriptor = { configurable: true.enumerable: true.value: 'No Cliff son transformation' };
const proxy = new Proxy(person, handler);
Object.defineProperty(proxy, 'name', descriptor);
console.log(proxy);

Copy the code

handler.deleteProperty

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * handler.deleteProperty(), which must return Boolean indicating whether the operation succeeded. * The interceptor can intercept the following operations: * 1, delete proxy[foo] and delete proxy.foo * 2, reflect.deleteProperty () */
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * target: propped object * prop: modified property name */
    deleteProperty(target, prop) {
        console.log(target === person); // true
        delete target[prop];
        return true; }};const proxy = new Proxy(person, handler);
delete proxy.name;
console.log(proxy); // { age: 30 }

Copy the code

handler.getOwnPropertyDescriptor

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * handler. GetOwnPropertyDescriptor (), must return objects. * the interceptor can intercept the following: * 1, Object. GetOwnPropertyDescriptor () * 2, Reflect getOwnPropertyDescriptor () * /
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * target: propped object * prop: modified property name */
    getOwnPropertyDescriptor(target, prop) {
        console.log(target === person); // true
        return Object.getOwnPropertyDescriptor(target, prop); }};const proxy = new Proxy(person, handler);
const descriptor = Object.getOwnPropertyDescriptor(proxy, 'name');
console.log(descriptor); // {value: '64x ',writable: false, Enumerable: true, different: true}

Copy the code

handler.getPrototypeOf

/* eslint-disable no-proto */
/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * Handler.getProtoTypeof (), which must return an object. * The interceptor can intercept the following operations: * 1, object.getProtoTypeof () * 2, reflect.getProtoTypeof () * 3, __proto__ * 3, instanceof * 3, the Object. The prototype. IsPrototypeOf () * /
// 1
const person = { name: 'No Cliff'.age: 30 };
Object.setPrototypeOf(person, { name: 'Wuyazi's Master' });
const handler = {
    /**
     * target:被代理对象
     */
    getPrototypeOf(target) {
        console.log(target === person); // true
        return Object.getPrototypeOf(target); }};const proxy = new Proxy(person, handler);
console.log(Object.getPrototypeOf(proxy)); // {name: 'wuyazi master'}
console.log(Reflect.getPrototypeOf(proxy)); // {name: 'wuyazi master'}
console.log(proxy.__proto__); // {name: 'wuyazi master'}

Copy the code

handler.has

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * handler.has(), must return Boolean. Foo in proxy * 2, foo in object.create (proxy) * 3, reflect.has () */
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * target: propped object * prop: modified property name */
    has(target, prop) {
        console.log(target === person); // true
        return prop intarget; }};const proxy = new Proxy(person, handler);
const boll = 'name' in proxy;
console.log(boll); // true

Copy the code

handler.isExtensible

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * Handler.isextensible (), must return Boolean. * The interceptor can block the following operations: * 1, Object.isextensible () * 2, Reflect.isextensible () */
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * target: propped object * prop: modified property name */
    isExtensible(target) {
        console.log(target === person); // true
        return Object.isExtensible(target); }};const proxy = new Proxy(person, handler);
console.log(Object.isExtensible(proxy)); // true
console.log(Reflect.isExtensible(proxy)); // true

Copy the code

handler.ownKeys

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * handler.ownkeys (), must return Boolean. * The interceptor can intercept the following operations: * 2 * 1, Object. GetOwnPropertyNames (), Object. GetOwnPropertySymbols (* 3), the Object. The keys () * 4, Reflect ownKeys () * /
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * @param target: propped object * @param prop: modified property name * @returns {Array} */
    ownKeys(target) {
        console.log(target === person); // true
        return Object.keys(target); }};const proxy = new Proxy(person, handler);
console.log(Object.keys(proxy)); // true[ 'name', 'age' ]
console.log(Object.getOwnPropertyNames(proxy)); // [ 'name', 'age' ]
console.log(Object.getOwnPropertySymbols(proxy)); / / []
console.log(Reflect.ownKeys(proxy)); // [ 'name', 'age' ]

Copy the code

handler.preventExtensions

/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * handler. PreventExtensions (), must return a Boolean. * the interceptor can intercept the following: * 1, Object. PreventExtensions () * 2, Reflect preventExtensions () * /
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * target: propped object * prop: modified property name */
    preventExtensions(target) {
        console.log(target === person); // true
        Object.preventExtensions(target);
        return true; }};const proxy = new Proxy(person, handler);
console.log(Object.preventExtensions(proxy)); // true
console.log(Reflect.preventExtensions(proxy)); // true

Copy the code

handler.setPrototypeOf

/* eslint-disable no-proto */
/* eslint-disable new-cap */
/* eslint-disable no-param-reassign */
/** * @author: const proxy =new proxy (target,handler); * @param {Object} target: the Object being propped * @param {Object} Handler: an Object whose properties are functions that define the behavior of the agent when an operation is performed. * @returns {Object} proxy: proxy Object * @description: proxy Object behavior. * handler.setPrototypeof (), must return Boolean. * the interceptor can intercept the following: * 1, Object. Handler. SetPrototypeOf () * 2, Reflect in handler. SetPrototypeOf (* 3), access Object __proto__ * /
// 1
const person = { name: 'No Cliff'.age: 30 };
const handler = {
    /** * @param target: propped object * @param prototype: propped object prototype */
    setPrototypeOf(target, prototype) {
        console.log(target === person); // true
        return Object.setPrototypeOf(target, prototype); }};const proxy = new Proxy(person, handler);
console.log(Object.setPrototypeOf(proxy, { name: 'Wuyazi's Master' })); // {name: 'wuyazi master'}
console.log(Reflect.setPrototypeOf(proxy, { name: 'Wuyazi's Master' })); // {name: 'wuyazi master'}
console.log((proxy.__proto__ = { name: 'Wuyazi's Master' })); // {name: 'wuyazi master'}

Copy the code

Reflect

Reflect.deleteProperty

/* eslint-disable no-proto */
/** * @author: const ret = reflect.deleteProperty (target, propertyKey) * @param: {Object} Target: target * @param: {String} propertyKey: indicates the property of the operation * @param: {Boolean} ret: indicates that the operation succeeded * @description: indicates that the property is deleted, similar to that of delete operator */
/ / the kunlun
const gongYangYu = { name: 'Ram feathers' };
// Define the wife property, cannot be deleted
const ret = Reflect.defineProperty(gongYangYu, 'wife', { value: 'Flower no answer'.enumerable: true.configurable: false });
console.log(ret); // true
console.log(gongYangYu.wife); / / no Chi flower
console.log(gongYangYu); // {name: 'ram feather ', wife:' Flower no answer '}
delete gongYangYu.wife;
console.log(gongYangYu); // {name: 'ram feather ', wife:' Flower no answer '}
const ret2 = Reflect.deleteProperty(gongYangYu, 'wife');
console.log(ret2); // false
console.log(gongYangYu); // {name: 'ram feather ', wife:' Flower no answer '}
const ret3 = Reflect.deleteProperty(gongYangYu, 'name');
console.log(ret3); // true
console.log(gongYangYu); // {wife: 'Beautiful no answer'}

Copy the code

Reflect.apply

/** * @author: thisArg argumentsList * const ret=Reflect. Apply (target, thisArg argumentsList) * @param: {Object} target: target function * @param: {Object} thisArg: function binding this Object * @param: {Array} argumentsList: argument list * @returns: {*} ret: the return value of the target function. * @description: The target function is called with the specified argument list. * /
/ / the kunlun
global.age = 19;
const liangXiao = function _liangXiao(name, ... data) {
    console.log(name); / / liang xiao
    console.log(data); // [' hua Xiao Frost ', 'Liu Ying Ying']
    console.log(this.age); / / 18
    return name;
};
console.time('reflect:');
const name = Reflect.apply(liangXiao, { age: 18},'liang xiao'.'Flower dawn Cream'.'Willow Warbler']);
console.log(name); / / liang xiao
console.timeEnd('reflect:'); / / reflect: : 3.972 ms
// Show performance loss
console.time('liangXiao:');
const name1 = liangXiao('liang xiao');
console.log(name1); / / liang xiao
console.timeEnd('liangXiao:'); / / 0.172 ms

Copy the code

Reflect.construct

/* eslint-disable no-proto */
/** * @author: const ret= reflect. construct(target, argumentsList[, function]) * @param: {Object} target: target function * @param: {Array} argumentsList: argument list * @param: {the Function} Function: the Function prototype for the prototype of the ret * @ the description: the equivalent of running the new target (... args). * ret.__proto__===prototype.prototype */
/ / the kunlun
global.age = 19;
const liangXiao = function _liangXiao(name, ... data) {
    console.log(data); // [' hua Xiao Frost ', 'Liu Ying Ying']
    this.name = name;
};
const proto = function _proto_() {};
proto.prototype = {
    construct: proto,
    getName() {
        return this.name; }};// After watching Kunlun in high school, I couldn't get over it for a long time. Suddenly look back, has changed a lot ah, no joy no sorrow.
const ret = Reflect.construct(liangXiao, ['liang xiao'.'Flower dawn Cream'.'Willow Warbler'], proto);
console.log(ret);
console.log(ret.__proto__ === proto.prototype); // true
console.log(ret.getName()); / / liang xiao
const prototype = Object.getPrototypeOf(ret);
console.log(prototype === proto.prototype); // true

Copy the code

Reflect.defineProperty

/* eslint-disable no-proto */
/** * @author: const ret = reflect.defineProperty (target, propertyKey, attributes) * @param: {Object} Target: the target Object * @param: {String} propertyKey: the property of the operation * @param: {Object} Attributes: the descriptor of the property * @param: {Boolean} ret: operation succeeded * @description: define attribute operator */
/ / the kunlun
const gongYangYu = { name: 'Ram feathers' };
const ret = Reflect.defineProperty(gongYangYu, 'wife', { value: 'Flower no answer'.enumerable: true });
console.log(ret); // true
console.log(gongYangYu.wife); / / no Chi flower
console.log(gongYangYu); // {name: 'ram feather ', wife:' Flower no answer '}

Copy the code

Reflect.isExtensible

Reflect.preventExtensions

/** * @author: Zhang Pengqin * const bool = Reflect. IsExtensible (Target); // Determine whether the object is extensible. ; * const bool = Reflect.preventExtensions(target); // Set the object to be unextensible. ; * /
const story = ['kunlun'.'the sea'];
console.log(Reflect.isExtensible(story)); // true
story.push(Flight of souls);
console.log(story); // [' n ', 'n ',' n ', 'n']
console.log(Reflect.preventExtensions(story)); // true
// story.push(' blood of heaven '); / / an error

Copy the code

Reflect.get

/* eslint-disable no-proto */
/** * @author: const ret = reflect. get(target, propertyKey[, receiver]) * @param: {Object} target: target * @param: {String} propertyKey: property of the operation * @param: {Object} Receiver: This value will be supplied to the target call if a getter is encountered. * @param: {*} ret: return value * @description: gets the value of the property, if the bound property has a getter method to call the getter,receiver is bound to the getter for this */
/ / the kunlun
console.log(Reflect.get(['9 like'.'peanuts'].1)); / / peanut
const jiuRu = {
    name: '9 like'.apprentice1: 'peanuts',
    get apprentice() {
        return `The ${this.name}The apprentices are:The ${this.apprentice1}`; }};console.log(Reflect.get(jiuRu, 'apprentice')); // Jiu Ru's apprentice is Peanut
console.log(Reflect.get(jiuRu, 'apprentice', { name: 'liang xiao'.apprentice1: 'the wind flow' })); // Liang Xiao's apprentice was Feng Yan

Copy the code

Reflect.getOwnPropertyDescriptor

/* eslint-disable no-proto */
/ * * * @ author: zhang qin * const climbing. Arr = Reflect getOwnPropertyDescriptor (target, propertyKey) * @ param: {Object} target: indicates the target Object * @param: {*} propertyKey: indicates the property of the target Object * @param: {Object} ret: indicates the return value * @description: indicates the property descriptor of the target Object. */ is available for both Symbol and non-enumerable
/ / the kunlun
const obj = {
    name: 'Xiao Qian Ju'[Symbol.for('Xiao Qian Ju')]: 'Xiao Qian Ju'};const parent = { designation: 'Black water rolls, and the world is swept.' };
obj.__proto__ = parent;
Object.defineProperty(obj, 'age', { value: 40.enumerable: false.configurable: false });
console.log(Reflect.getOwnPropertyDescriptor(obj, 'name')); // {value: '64x ', writable: true, Enumerable: true, different: true}
console.log(Reflect.getOwnPropertyDescriptor(obj, Symbol.for('Xiao Qian Ju'))); // {value: '64x ', writable: true, Enumerable: true, different: true}
console.log(Reflect.getOwnPropertyDescriptor(obj, 'age')); // { value: 40, writable: false, enumerable: false, configurable: false }

Copy the code

Reflect.has

/* eslint-disable no-proto */
/** * @author: const ret = reflect. has(target, propertyKey, value[, receiver]) * @param: {Object} target: target Object * @param: {String} propertyKey: operation property * @param: {Boolean} ret: return value * @description: Symbol = */; Symbol = Symbol; Symbol = Symbol
/ / the kunlun
const obj = {
    name: 'Xiao Qian Ju'[Symbol.for('Xiao Qian Ju')]: 'Xiao Qian Ju'};const parent = { designation: 'Black water rolls, and the world is swept.' };
obj.__proto__ = parent;
Object.defineProperty(obj, 'age', { value: 40.enumerable: false.configurable: false });
console.log(obj); // {name: 'xiao qian'}
console.log(obj.designation); // Black water surging, sweeping the world
// Determine its own attributes, can not be enumerated
console.log(Reflect.has(obj, 'age')); // true;
// Determine the type of Symbol
console.log(Reflect.has(obj, Symbol.for('Xiao Qian Ju'))); // true;
// Determine the attributes on the prototype
console.log(Reflect.has(obj, 'designation')); // true;

Copy the code

Reflect.ownKeys

/* eslint-disable no-proto */
/** * @author: * const arr = Reflect. OwnKeys (target); * @param: {Object} target: target Object * @param: {Array} ret: return value * @description: get all attributes of itself, including attributes that cannot be enumerated,Symbol */
/ / the kunlun
const obj = {
    name: 'Xiao Qian Ju'[Symbol.for('Xiao Qian Ju')]: 'Xiao Qian Ju'};const parent = { designation: 'Black water rolls, and the world is swept.' };
obj.__proto__ = parent;
Object.defineProperty(obj, 'age', { value: 40.enumerable: false.configurable: false });
console.log(Reflect.ownKeys(obj));

Copy the code

Reflect.getPrototypeOf

Reflect.setPrototypeOf

/* eslint-disable no-proto */
/** * @author: Const obj= reflect. getPrototypeOf(target)// Returns null * const Bool = reflect. setPrototypeOf(target,proto)// Set the prototype of target, set it to return true * @description: */
const obj = {
    name: 'Xiao Qian Ju'[Symbol.for('Xiao Qian Ju')]: 'Xiao Qian Ju'};const parent = { designation: 'Black water rolls, and the world is swept.' };
obj.__proto__ = parent;
console.log(Reflect.getPrototypeOf(obj)); // the screen for the screen, and the screen for the screen;
console.log(Reflect.setPrototypeOf(obj, { age: 30 })); // true
console.log(obj.__proto__); // { age: 30 }

Copy the code

Reflect.set

/* eslint-disable no-proto */
/** * @author: const ret = reflect. set(target, propertyKey, value[, receiver]) * @param: {Object} Target: the target Object * @param: {String} propertyKey: the property of the operation * @param: {*} value: the value of the property set * @param: {Object} receiver: If a setter is encountered, receiver binds the getter to this * @param: {Boolean} ret: return value * @description: just like setting a property on an Object. * /
/ / the kunlun
const jiuRu = {
    name: '9 like'.apprentice1: 'peanuts',
    set apprentice(apprentice1) {
        this.apprentice1 = `${apprentice1}--The ${this.age}`; }};Reflect.set(jiuRu, 'name'.'Master Jiuru');
console.log(jiuRu); // {name: 'apprentice ', apprentice: [Setter]}
const thisArg = { age: 18 };
Reflect.set(jiuRu, 'apprentice'.'peanuts', thisArg);
console.log(jiuRu); // {name: 'apprentice ', apprentice: [Setter]}
console.log(thisArg); // {age: 18, apprentice1: 'peanut --18'}

Copy the code

Promise

/* eslint-disable prefer-promise-reject-errors */
/** * @author: Zhang Panchin * @description:Promise Asynchronous programming * A Promise has the following states: Once the state is represented, it cannot be changed * pending: The initial state, which is neither successful nor failed. This is a big pity: The waiting state will change gradually. Then processing logic * Rejected: Indicates that the operation fails. Catch processing logic * each THEN returns a new Promise instance */
// 1. new Promise();
const func = function _func(movie) {
    return new Promise((resolve, reject) = > {
        if (movie === Inception) {
            resolve('Dream big.');
        } else {
            // Good Will Hunting
            reject('Success does not mean what you want to achieve, but how far you have come from the beginning of that struggle. '); }}); }; func(Inception)
    .then((data) = > {
        console.log(data); // Dream big
    })
    .catch((error) = > {
        console.log(error);
    });
func('Heart Catcher')
    .then((data) = > {
        console.log(data);
    })
    .catch((error) = > {
        console.log(error); // Success does not mean what you want to achieve, but how far you have come from the beginning of that struggle.
    });

Copy the code

Promise.all

/** * @author: const promi= promise. all(iterable); * @description: The method returns a Promise instance, or contains all resolve(data), a reject state, which changes the state of the returned instance to Reject */
const sleep = function _sleep(ms) {
    return new Promise((resolve) = > {
        setTimeout((a)= > {
            resolve();
        }, ms);
    });
};
const sleep1 = sleep(1000).then((a)= > {
    console.log('Take a break');
    return 'Tell him I'm sorry. I'm going to find a girl.';
});
const sleep2 = sleep(2000).then((a)= > {
    console.log('Take a two-second break');
    return 'Forget what should be forgotten, and face what can be in the future. ';
});
const sleep3 = sleep(3000).then((a)= > {
    console.log('Take a three-second break');
    return 'Boy, life isn't about books and assumptions. It's about feeling. ';
});
const sleep4 = sleep(4000).then((a)= > {
    console.log('Take a four-second break');
    return 'Everyone has bad days, but it can also remind you of the good things you didn't care about before. ';
});
const sleep5 = sleep(5000).then((a)= > {
    console.log('Take a five second break');
    throw new Error('Simulated test failure situation');
});
Sleep2 is executed first, so sleep2 is returned. Because the event is already in the queue, the rest of the promises will be executed
// const ret = Promise.all([sleep1, sleep2, sleep3, sleep4]);
// ret.then((data) => {
// // Array of all Promise resolve(data) data
// console.log(data);
// }).catch((error) => {
// console.log(error.message);
// });
// Rest for a second;
// Rest for two seconds;
// Rest for three seconds;
// Take a four-second break
// [(' Tell him I'm sorry, I'm going to find a girl ', 'Forget what SHOULD be forgotten and face what can be in the future. ',' Son, life is not made by books and things you take for granted, it's made by the heart. ', 'Some people have bad times, but it will also remind you of the good things you didn't care about before. ')];
const ret2 = Promise.all([sleep1, sleep2, sleep3, sleep4, sleep5]);
ret2.then((data) = > {
    // All promise resolve(data) data arrays
    console.log(data);
}).catch((error) = > {
    console.log(error.message); // Execute this
});
// Rest for a second;
// Rest for two seconds;
// Rest for three seconds;
// Rest for four seconds;
// Rest for five seconds;
// Simulate test failure;

Copy the code

Promise.race

/** * @author: const promise = promise. race(iterable); The @description: method returns a promise, which is returned whenever the first state in the iterator changes
const sleep = function _sleep(ms) {
    return new Promise((resolve) = > {
        setTimeout((a)= > {
            resolve();
        }, ms);
    });
};
const sleep2 = sleep(2000).then((a)= > {
    console.log('Take a two-second break');
    return 'You can understand everything, but the only way to get to the bottom of it is to try. ';
});
const sleep3 = sleep(3000).then((a)= > {
    console.log('Take a three-second break');
    return 'Man is a lonely individual after all, even if you have been in the arms of others, the only difference between people, perhaps, is where you hide your loneliness. ';
});
const sleep4 = sleep(4000).then((a)= > {
    console.log('Take a four-second break');
    return 'Shunned and distrusted because I was abandoned by the one who should have loved me. ';
});
Sleep2 is executed first, so sleep2 is returned. Because the event is already in the queue, the rest of the promises will be executed
const ret = Promise.race([sleep2, sleep3, sleep4]);
ret.then((data) = > {
    console.log(data); // You can understand everything, but the only way to get to the bottom of it is to try.
}).catch((error) = > {
    console.log(error.message);
});
// Pass the result of the run
// Take a two-second break
// You can understand everything, but the only way to get to the bottom of it is to try.
// Take a three-second break
// Take a four-second break

Copy the code

Promise.resolve

// 1. Gus van Sant (Good Will Hunting)
Promise.resolve('You don't know true loss, because that can only be realized by loving someone more than yourself, and I don't think you dare love like that. ')
    .then((data) = > {
        console.log(data); / / execution
    })
    .catch((error) = > {
        console.log(error);
    });
Promise.resolve('You don't know true loss, because that can only be realized by loving someone more than yourself, and I don't think you dare love like that. ')
    .then((data) = > {
        console.log(data); / / execution
        throw new Error('Our little foibles lead us to the right person. '); // Simulation error
    })
    .then((a)= > {
        console.log('Last instance error, catch'); / / for execution
    })
    .catch((error) = > {
        console.log(error.message); // Execution, our little foibles, lets us find the right person.
    });

Copy the code

async

/** * @author: @description: Async returns a Promise object that can be added to a callback using the then method. * When a function executes, it will return once it encounters await, wait until the asynchronous operation is complete, and then execute the following statement in the function body. * /
// 1. Wait for the await to finish before executing the following statement.
const awaitFunc = function _awaitFunc() {
    return Promise.resolve('awaitFunc').then((data) = > {
        console.log(data);
        return 'awaitFunc-then-return-data';
    });
};
const async = async function _async() {
    // Wait for the await to finish before putting further code into the microtask queue
    await awaitFunc().then((data) = > {
        console.log(data);
    });
    console.log('awaitFunc finishes printing ');
};
async(a);/** * awaitFunc * awaitFunc-then-return-data * awaitFunc finishes printing */
const noAwaitFunc = function _noAwaitFunc() {
    return Promise.resolve('noAwaitFunc').then((data) = > {
        console.log(data);
        return 'noAwaitFunc-then-return-data';
    });
};
const noAsync = function _noAsync() {
    noAwaitFunc().then((data) = > {
        console.log(data);
    });
    console.log('noAwaitFunc finishes printing ');
};
noAsync();
/** * noAwaitFunc prints * noAwaitFunc * noAwaitFunc-then-return-data */

Copy the code
/* eslint-disable no-unused-vars */
function sleep(ms) {
    return new Promise((resolve) = > {
        setTimeout((a)= > {
            resolve(`sleep for ${ms} ms`);
        }, ms);
    });
}
// 1
async function asyncFunction() {
    console.time('asyncFunction total executing:');
    const sleep1 = await sleep(1000);
    console.log(`sleep1: ${sleep1}`);
    const sleep2 = await sleep(2000);
    console.log(`sleep2: ${sleep2}`);
    const sleep3 = await sleep(3000);
    console.log(`sleep3: ${sleep3}`);
    const sleep4 = await sleep(4000);
    console.log(`sleep4: ${sleep4}`);
    const sleep5 = await sleep(5000);
    console.log(`sleep5: ${sleep5}`);
    console.timeEnd('asyncFunction total executing:');
    return 'asyncFunction done.'; // This does not have to be returned. This is just a mark to show the flow
}
// 2
async function asyncFunction2() {
    console.time('asyncFunction2 total executing:');
    const promiseAll = await Promise.all([sleep(1000), sleep(2000), sleep(3000), sleep(4000), sleep(5000)]);
    console.timeEnd('asyncFunction2 total executing:');
    console.log(promiseAll); // [ 'sleep for 1000 ms','sleep for 2000 ms','sleep for 3000 ms','sleep for 4000 ms','sleep for 5000 ms' ]
    return 'asyncFunction2 done.'; // This does not have to be returned. This is just a mark to show the flow
}
// asyncFunction total Executing :: 15023.078ms
// asyncFunction().then(data => console.log(data));
// asyncFunction2 Total Executing :: 5004.143ms
// asyncFunction2();

Copy the code
/* eslint-disable no-unused-vars */
function sleep(ms) {
    return new Promise((resolve) = > {
        setTimeout((a)= > {
            const str = `sleep for ${ms} ms`;
            console.log(str);
            resolve(`resolve-${str}`);
        }, ms);
    });
}

async function asyncFunction2() {
    console.time('asyncFunction2 total executing:');
    const promiseRace = await Promise.race([sleep(1000), sleep(2000), sleep(3000), sleep(4000), sleep(5000)]);
    console.timeEnd('asyncFunction2 total executing:');
    console.log(promiseRace); // [ 'sleep for 1000 ms','sleep for 2000 ms','sleep for 3000 ms','sleep for 4000 ms','sleep for 5000 ms' ]
    return 'asyncFunction2 done.'; // This does not have to be returned. This is just a mark to show the flow
}
asyncFunction2().then(data= > console.log(data));
/** * sleep for 1000 ms asyncFunction2 total executing:: 1006.042ms resolve-sleep for 1000 ms asyncFunction2 done. Sleep for 2000 MS sleep for 3000 ms sleep for 4000 ms sleep for 5000 ms */

Copy the code

Map

/* eslint-disable no-restricted-syntax */
/** * @author: New Map([iterable]) * @param {iterable} Iterable can be an array or other iterable object * @description:Map holds key/value pairs. Any value (object or raw value) can be a key or a value. * /
Iterable [[key,value],[key,value]]
const arr = [['name'.'batman'], ['age'.'27']].const map = new Map(arr);
console.log(map.get('name')); // batman
console.log(map.get('age')); / / 27

/ / 2.
const map1 = new Map(a); map1.set('name'.'Wonder Woman');
map1.set('gender'.'beauty');
console.log(map1.get('name')); // Wonder Woman
console.log(map1.get('gender')); / / the beauty

// 3.map.prototype.clear () removes all key/value pairs from the Map object.
map1.clear();
console.log(map1.get('name')); // undefined
console.log(map1.get('gender')); // undefined

// 4.Map.prototype.delete(key)
// If the element exists in the Map object, remove it and return true; Otherwise return false if the element does not exist
const arr2 = [['name'.'the sea king'], ['age'.'27']].const map4 = new Map(arr2);
console.log(map4.get('name')); / / the sea king
// Delete exists returns true
console.log(map4.delete('name')); // true
console.log(map4.get('name')); // undefined
// There is no deletion, false
console.log(map4.delete('name')); // false

// 5.map.prototype. has(key) returns a Boolean value indicating whether the Map instance contains the value corresponding to the key.
const arr5 = [['name'."Superman"], ['age'.'27']].const map5 = new Map(arr5);
console.log(map5.has('name')); // true
map5.delete('name');
console.log(map5.has('name')); // false
// 6.Map.prototype.keys()
// Returns a new Iterator containing the keys of each element in the Map in insertion order.
const arr6 = [['name'."Superman"], ['age'.'27']].const map6 = new Map(arr6);
const iterator = map6.keys();
for (const item of iterator) {
    console.log(item); // name age;
}
// 7.map.prototype.values () returns a new Iterator containing the values of each element in the Map in insertion order.
const arr7 = [['name'."Superman"], ['age'.'27']].const map7 = new Map(arr7);
const iterator7 = map7.values();
for (const item of iterator7) {
    console.log(item); / / superman's 27
}
// 8.map.prototype.entries () returns a new Iterator containing the [key, value] array of each element in the Map in insertion order.
const arr8 = [['name'."Superman"], ['age'.'27']].const map8 = new Map(arr8);
const iterator8 = map8.entries();
for (const [key, value] of iterator8) {
    console.log(key); // name age
    console.log(value); / / superman's 27
}

Copy the code

Map.prototype.forEach

/** * @author: prototype.forEach(callback(value[,key[, Map]])[, thisArg]) Method executes the callbacks provided in the parameters once for each key-value pair in the Map object, in insertion order. * @ param {*} value: the value * @ param {*} key: key * @ param Map for {} Map: method is called Object * @ param {Object} thisArg: callback executes this, Arrow functions cannot bind this */
const arr = [['movie-1'.'Shawshank Redemption'], ['movie-2'.Forrest Gump]].const movie = new Map(arr);
movie.forEach((value, key, map) = > {
    console.log(value);
    console.log(key);
    console.log(map);
});

Copy the code

Set

/* eslint-disable no-restricted-syntax */
/** * @author: const set = new set ([iterable]); * @description: The Set object allows you to store a unique value of any type, either a primitive value or an object reference. * /
/ / 1.
const movie = { movie: 'focus' };
const set1 = new Set([1.1, movie, movie, 2.3]);
console.log(set1); // Set {1, {movie: 'focus'}, 2, 3}
// How many elements
console.log(set1.size); / / 4
// Add elements
set1.add(The Matrix);
console.log(set1); // {1, {movie: 'focus'}, 2, 3,' Matrix '}
// Delete elements
set1.delete(1);
console.log(set1); // Set {{movie: 'focus'}, 2, 3,' Matrix '}
// Determine whether an element is included
console.log(set1.has(2)); // true
console.log(set1.has(21)); // false
Set.prototype.entries() returns a new iterator object,
const it = set1.entries();
for (const [key, value] of it) {
    // Key, like value, is an element of set
    console.log(key);
    console.log(value);
}
// set.prototype.keys () behaves the same as set.prototype.values ()
const values = set1.values();
for (const value of values) {
    console.log(value);
    /** * {movie: 'focus'} * 2 * 3 * Matrix */
}

Copy the code

Set.prototype.forEach

/** * @author: Set.prototype. Callback ([currentKey[, currentKey[, setKey]]])[, ThisArg]) * @param {*} currentKey * @param {*} Set ThisArg will bind this to the callback function, the arrow function will not bind * @description: Execute the provided callback functions in order of insertion of elements in the collection. * /
const set = new Set(['Batman Begins'.'The Dark Knight of Batman'.'Rise of the Dark Knight.']);
set.forEach((key, val, set1) = > {
    console.log(key);
    console.log(set1);
    console.log(val);
});
console.log(set);

Copy the code

Math

/** * @author: * Math.LN2, the natural logarithm of 2, is approximately equal to 0.693. * Math.LN10, the natural logarithm of 10, is approximately equal to 2.303. * Math.LOG2E, * Math.log10e, logarithm base 10 of E, is approximately 0.434. * Math.pi, PI, the ratio of the circumference to the diameter of a circle, is approximately 3.14159. * math.sqrt1_2, The square root of 1/2 is approximately 0.707. * math. SQRT2, the square root of 2 is approximately 1.414. */
Math.abs(x), returns the absolute value of x. The number will be converted to remove the absolute value
console.log(Math.abs(- 1)); / / 1
console.log(Math.abs(1)); / / 1
console.log(Math.abs(0)); / / 1
console.log(Math.abs(+0)); / / 1
console.log(Math.abs('_Elsa')); // NaN
console.log(Math.abs('1')); / / 1
Math.ceil(x) returns the rounded value of x: the smallest integer greater than or equal to x
console.log(Math.ceil(1.1)); // -1
console.log(Math.ceil(1.2)); / / 2
console.log(Math.ceil('1.1')); // -1
console.log(Math.ceil('_Elsa')); // Nan
console.log(Math.ceil(1)); / / 1
Math.floor(x) : the smallest integer less than or equal to x
Math.floor(45.95); / / 45
Math.floor(45.05); / / 45
Math.floor(4); / / 4
Math.floor(45.05); / / - 46
Math.floor(45.95); / / - 46
// 4. math.max ([x[,y[,...]]]) returns 0 to the maximum value of multiple values.
console.log(Math.max(1.2.3)); / / 3
console.log(Math.max(1.2.3.'4')); / / 4
console.log(Math.max(1.2.3.'4'.'asdfa')); // NaN
console.log(Math.max(1.2.3.'4'.'4.5')); / / 4.5
console.log(Math.max(1.2.3.'4'.'4.5'.'4.5')); / / 4.5
Math.min([value1[,value2,...]]) returns the minimum value.
console.log(Math.min(1.2.3)); / / 1
console.log(Math.min(1.2.3.'4')); / / 1
console.log(Math.min(1.2.3.'4'.'asdfa')); // NaN
console.log(Math.min(1.2.3.'4'.'4.5')); / / 1
console.log(Math.min(1.1.2.3.'4'.'4.5'.'4.5')); / / 1
// 6.Math.random() random number within this range [0,1]
console.log(Math.random()); / / 0.29555726609770505
Math.round(x) returns the rounded integer.
console.log(Math.round(4.3)); / / - 4
console.log(Math.round(4.3)); / / 4
console.log(Math.round('4.3')); / / 4
console.log(Math.round('4.as3')); // NaN

Copy the code

Number

// 1.number.isnan () determines whether the value passed is a NaN.
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(1)); // false
console.log(Number.isNaN('NaN')); // false
// 2. Number.isfinite () returns true only when the passed value type is "Number" (finite).
// positive infinity
console.log(Number.isFinite(Infinity)); // false
// Nan
console.log(Number.isFinite(NaN)); // false
// Negative infinity
console.log(Number.isFinite(-Infinity)); // false
console.log(Number.isFinite(0)); // true
console.log(Number.isFinite(2e64)); // true
console.log(Number.isFinite('0')); // false

IsInteger () determines that the value type passed is "Number" and is an integer.
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(- 100000.); // true

Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false

Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger('10'); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false

Const ret= number.parseint (string[, radix]); const ret= number.parseint (string[, radix]
// radix specifies the radix, i.e. the number of digits in which a string is represented
const strObj = '0110';
console.log(Number.parseInt(strObj, 2)); / / 6
console.log(Number.parseInt(strObj, 10)); / / 110
console.log(Number.parseInt('asdfas'.10)); // NaN

Copy the code

Regexp

/** * @author: Const regexp=new regexp (pattern [, flags]) * @param {String} regular expression * @param {String} flags * Flags can be the following combinations * g: Global matching; Find all matches, not stop after the first * I: ignore case * y: sticky match; If a match is successful, it starts with the rest of the string. If no match is found, there is no subsequent result. * regexp. LastIndex g, y mode takes effect, records the position of the next match, and if the match fails, the value will be 0 * @description: The match will match the result that the regular expression needs to match */
// 0. The regular expression matches as much as possible
const str = 'aaaa11aaaa11aaaa11';
const regexp = /a+/g;
console.log(regexp.exec(str)); // [ 'aaaa', index: 0, input: 'aaaa11aaaa11aaaa11' ]
console.log(regexp.exec(str)); // [ 'aaaa', index: 6, input: 'aaaa11aaaa11aaaa11' ]
console.log(regexp.exec(str)); // [ 'aaaa', index: 12, input: 'aaaa11aaaa11aaaa11' ]
// 0-1 without g
const str0 = 'abc11abbc11abbbc';
const reg0 = new RegExp('ab+c');
const ret01 = reg0.exec(str0);
const ret02 = reg0.exec(str0);
const ret03 = reg0.exec(str0);
console.log(ret01); // [ 'abc', index: 0, input: 'abc11abbc11abbbc' ]
console.log(ret02); // [ 'abc', index: 0, input: 'abc11abbc11abbbc' ]
console.log(ret03); // [ 'abc', index: 0, input: 'abc11abbc11abbbc' ]
// 1.g
const str1 = 'abc11abbc11abbbc';
const reg1 = new RegExp('ab+c'.'g');
const ret1 = reg1.exec(str1);
const ret2 = reg1.exec(str1);
const ret3 = reg1.exec(str1);
console.log(ret1); // [ 'abc', index: 0, input: 'abc11abbc11abbbc' ]
console.log(ret2); // [ 'abbc', index: 5, input: 'abc11abbc11abbbc' ]
console.log(ret3); // [ 'abbbc', index: 11, input: 'abc11abbc11abbbc' ]
// 2.i
const str3 = 'aaaa11aaaa11aaaa11';
const regexp3 = /aA+/i;
console.log(regexp3.exec(str3)); // [ 'aaaa', index: 0, input: 'aaaa11aaaa11aaaa11' ]
console.log(regexp3.exec(str3)); // [ 'aaaa', index: 6, input: 'aaaa11aaaa11aaaa11' ]
console.log(regexp3.exec(str3)); // [ 'aaaa', index: 12, input: 'aaaa11aaaa11aaaa11' ]
// 3.y
const str4 = 'aaaa11aaaa11aaaa11';
const regexp4 = /aa/y;
// The first run matches aaAA11AAaa11AAaa11, leaving 11AAAA11AA11
console.log(regexp4.exec(str4)); // [ 'aa', index: 0, input: 'aaaa11aaaa11aaaa11' ]
// The second run matches 11AAAA11AAAA11
console.log(regexp4.exec(str4)); // [ 'aa', index: 2, input: 'aaaa11aaaa11aaaa11' ]
console.log(regexp4.exec(str4)); // null
// regexp.prototype.test () is used to check whether the regular expression matches the specified string. Returns true or false.
const str5 = 'aaaa11aaaa11aaaa11';
const regexp5 = /aa/y;
console.log(regexp5.test(str5)); // true
console.log(regexp5.test(str5)); // true
// Match failed, lastIndex set to 0
console.log(regexp5.test(str5)); // false
// The match is successful and lastIndex is set to 2
console.log(regexp5.test(str5)); // true
Copy the code

Date

/** * @author: @description: The Date object is based on the Unix Time Stamp, i.e. the number of milliseconds since January 1, 1970 (UTC). * /
// 1. new Date(); Obtain the current system time
const now = new Date(a);console.log(now); / / the T14:2019-05-31 33:47. 439 z
// 2.new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
// monthIndex starts with 0
const thatData = new Date(2019.2.14.19.30);
console.log(thatData); // Thu Mar 14 2019 19:30:00 GMT+0800
console.log(thatData.toUTCString()); // Thu Mar 14 2019 19:30:00 GMT+0800
// 3. const milliseconds = Date.UTC(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
const milliseconds = Date.UTC(2019.2.14.19.30);
console.log(milliseconds); / / 1552591800000
// 4.new Date(milliseconds); 1970-1-1 The time elapsed in milliseconds
const thatDay = new Date(milliseconds);
console.log(thatDay); / / the 2019-03-14 T19:30:00. 000 z

Copy the code

Date-get Obtains attributes

const mill = Date.UTC(2019.2.14.19.30.21.21.21);
console.log(mill); / / 1552591821021
const thatDay = new Date(mill);
// 1.date.prototype.getDate () returns the day of the month (1-31) of the specified Date object based on local time.
console.log('thatDay.getDate():', thatDay.getDate()); / / 15

/ / 2. The Date. The prototype. GetUTCDate () returns a specific Date object according to the world on which day (1-31).
console.log('thatDay.getUTCDate():', thatDay.getUTCDate()); / / 14

// 3.date.prototype.getTime () returns the number of milliseconds since 1970-1-1 00:00:00 UTC,
console.log('thatDay.getTime():', thatDay.getTime()); / / 1552591821021

Date.prototype.getday () returns the day of the week (0-6) of the specified Date object based on local time.
console.log('thatDay.getDay():', thatDay.getDay()); / / 5

/ / 5. Date. Prototype. GetUTCDay () according to the world to return to a specific Date object which day of the week (0-6).
console.log('thatDay.getUTCDay():', thatDay.getUTCDay()); / / 4

// 6.Date.prototype.getHours(); Returns the hour (0-23) of the specified date object based on local time.
console.log('thatDay.getHours():', thatDay.getHours()); / / 3

/ / 7. Date. Prototype. GetUTCHours () based on the current world returned to a certain Date object hours (0-23).
console.log('thatDay.getUTCHours():', thatDay.getUTCHours()); / / 19

// Date.prototype.getMilliseconds(); Returns the milliseconds (0-999) of the specified date object based on local time.
console.log('thatDay.getMilliseconds():', thatDay.getMilliseconds()); / / 21

/ / Date. Prototype. GetUTCMilliseconds () according to universal time to return to a specific Date objects, the number of milliseconds (0-999).
console.log('thatDay.getUTCMilliseconds():', thatDay.getUTCMilliseconds()); / / 21

// Date.prototype.getMinutes(); Returns the minutes (0-59) of the specified date object based on local time.
console.log('thatDay.getMinutes():', thatDay.getMinutes()); / / 30

/ / Date. Prototype. GetUTCMinutes () according to universal time to return to a specific Date object on the number of minutes (0-59).
console.log('thatDay.getUTCMinutes():', thatDay.getUTCMinutes()); / / 30

// Date.prototype.getMonth(); Returns the month (0-11) of the specified date object based on local time.
console.log('thatDay.getMonth():', thatDay.getMonth()); / / 2

/ / Date. Prototype. GetUTCMonth () return in specific Date objects according to universal time (0-11).
console.log('thatDay.getUTCMonth():', thatDay.getUTCMonth()); / / 2

// Date.prototype.getSeconds(); Returns the number of seconds (0-59) of the specified date object based on local time.
console.log('thatDay.getSeconds():', thatDay.getSeconds()); / / 21

/ / Date. Prototype. GetUTCSeconds () according to universal time to return to a specific Date object number of seconds (0-59).
console.log('thatDay.getUTCSeconds():', thatDay.getUTCSeconds()); / / 21

Copy the code

other

var,let,const

// 1. Block level scope
{
    const a = 1;
    let b = 2;
    // eslint-disable-next-line no-var
    var c = 3;
}
// console.log(a); // ReferenceError: a is not defined
// console.log(b); // ReferenceError: a is not defined
console.log(c); / / 3

// 2. There is no variable promotion
console.log(foo); / / output is undefined
var foo = 2;
// console.log(bar); / / error ReferenceError
let bar = 2;

// 3. Temporary dead zone (TDZ): A variable is unavailable in a code block until it is declared with the let command.
var d = 'd';
try {
    if (true) {
        ReferenceError: d is not defined
        d = 'd'; // TDZ-begin
        console.log(d);

        let d = 'c'; // TDZ-end
        console.log(d); // c}}catch (error) {
    console.log(error.message); // d is not defined
}

// 3-1, in the same scope, not allowed to declare the same variable, different block level can
let e = '3';
if (true) {
    let e = 'e';
    // Defining var is an error
    // var e = 'var-e';
    console.log(e); // e
}
// 4. Not recommended: ES6 introduces block-level scopes that explicitly allow functions to be declared in block-level scopes.
(function _execFunction() {
    let f;
    if (true) {
        f = function _f() {
            console.log('Overhanging mountain');
            console.log(The Great Wall of Swords); }; } f(); } ());Copy the code

closure

A closure is a function that has access to a variable in the scope of another function. Function A contains function B. Execute function A, return B; B is the closure. * /
// 1. Variable C references _C, run C(); The returned object accesses local variables in C, causing C not to be reclaimed.
const C = function _C() {
    // const a = { name: 'name' };
    const getA = function _getA() {
        return '11';
    };
    return { getA };
};
const ret = C();
console.log(ret.getA()); // { name: 'name' }
// // self-executing function
// const retC = (function _C(obj2) {
// const a = { name: 'name' };
// const data = obj2;
// const getA = function _getA() {
// return a;
/ /};
// const setA = function _setA(obj) {
// Object.assign(a, obj);
/ /};
// return { getA, setA, data };
// }({ age: 18 }));
// console.log(retC.data); // { age: 18 }
// console.log(retC.getA()); // { name: 'name' }

Copy the code
/** * View execution context in stack * execution context {* Scope chain: [[scope]], which was determined when the function was created. If you can't find it, go to the parent scope. * Variable objects: Used to store variables and function declarations defined in context. * thisArg: When executing code, confirm this pointer *} * function call, variable object (VO) programming (AO) */
const A = function _A(data) {
    const a1 = 'a';
    const b1 = 'a-b1';
    // const c1 = 'a-c1';
    const b = function _b() {
        // const b1 = 'b';
        // const c1 = 'b-c1';
        const c = function _c() {
            const c1 = 'c';
            const d = function _d() {
                const d1 = `${data}-${a1}-${b1}-${c1}`;
                return {
                    a1,
                    b1,
                    c1,
                    d1,
                };
            };
            return d;
        };
        return c();
    };
    return b();
};
// The function returned by [[scope]] defines the value of the desired variable.
const a = A('A');
console.log(a());

Copy the code

Prototype and prototype chain

/* eslint-disable func-names */
/* eslint-disable no-proto */
/** * [JS new does exactly what?] (https://juejin.cn/post/6844903456667336712) * [JS prototype chain and inheritance don't asked again fall] * (https://juejin.cn/post/6844903475021627400) [from the prototype and __proto__ spy JS source of inheritance] (https://juejin.cn/post/6844903475155828749) * @ author: zhang qin * @ climbing the description: * Every object (including functions) has a __proto__ attribute, which has been added to the specification in ES6. * __proto__ is an internal attribute of an object that points to the constructor's prototype. The object relies on it to query the prototype chain, and instanceof relies on it to determine whether or not the object is inherited. __proto__ (obJ, obJ, obJ, obJ, obj, obj, obj, obj) * const A =function _A(){} * const A =new A(); * What does the new keyword mention? Const temp={}; Temp.__proto__= a.prototype; * 3, A.c all (temp); Replace this in A with temp, and assign the temp return to A; * /
// "In the Snow"
// 1. Object __proto_ property
const A = { wife: { name: 'the luoyang'}};const B = { faShu: True Martial Artist };
const C = { name: 'Xu Fengnian' };
// Object.setPrototypeOf(xuFengNian, qianShi); This is recommended
B.__proto__ = A;
C.__proto__ = B;
Obj = obj; obj = obj; obj = obj; obj = obj; obj = obj; obj = obj;
console.log(C.wife); // {name: 'luoyang'}
console.log(C.faShu); // True Martial artist
console.log(C.name); / / Xu Fengnian
// 2. Verify the new keyword
const D = function _D(name) {
    this.name = name;
    this.play = function _play() {
        console.log(1211);
    };
};
D.prototype = {
    constructor: D,
    getName() {
        return this.name; }};// Execute the constructor to return the instance
const d = new D('Hung Siu Image');
// a.__proto__=A.prototype;
console.log(d.__proto__ === D.prototype); // true
// Point this to obj
console.log(d.getName()); / / hung like washing
d.play(); // Verify that this refers to obj

Copy the code

The prototype chain implements inheritance

/* eslint-disable no-proto */
/** * @author: Zhang Panqin * @description: Implementation of inheritance based on prototype chain. * /
// 1. Implement inheritance through the prototype chain
const A = function _A() {};
A.play = function _play() {
    console.log('A.paly');
};
const B = function _B() {};
B.study = function _study() {
    console.log('B.study');
};
const C = function _C() {};
C.sleep = function _sleep() {
    console.log('C.sleep');
};
B.__proto__ = C;
A.__proto__ = B;
A.study(); // B.study
A.sleep(); // C.sleep
The attribute data of the prototype obj points to the reference type. Subclasses based on the prototype obj will share data. One subclass will change, and the rest will be affected.
B.names = ['Xu Xiao'.'Wu Su'.'Tsui Chi Hu'.'Tsui Wei Xiong'.'Xu Fengnian'.'Xu Long Elephant'];
const D = function _D() {};
D.__proto__ = B;
console.log(A.names); // [' Xu Xiao ', 'Wu Su ',' Xu Zhihu ', 'Xu Weixiong ',' Xu Fengnian ', 'Xu Longxiang']
console.log(D.names); // [' Xu Xiao ', 'Wu Su ',' Xu Zhihu ', 'Xu Weixiong ',' Xu Fengnian ', 'Xu Longxiang']
A.names.push('ginger mud');
D.names.push('Nangong Servant shot');
console.log(A.names); / / [' Xu Xiao ', 'Wu Su', 'xu fat tiger', 'Xu Weixiong', 'Xu Fengnian', 'syrmosaurus like', 'ginger mud', 'the nangongshan servant shoot']
console.log(D.names); / / [' Xu Xiao ', 'Wu Su', 'xu fat tiger', 'Xu Weixiong', 'Xu Fengnian', 'syrmosaurus like', 'ginger mud', 'the nangongshan servant shoot']
Copy the code

The constructor and the stereotype chain are combined to implement inheritance

/* eslint-disable no-proto */
/** * @author: @description: Implement inheritance based on constructor and prototype chain. * /
// 1. A inherits B and B inherits C through the prototype chain and constructor
const C = function _C(roles = ['Xu Xiao'.'Wu Su'.'Tsui Chi Hu'.'Tsui Wei Xiong'.'Xu Fengnian'.'Xu Long Elephant']) {
    this.roles = roles;
    this.c = function _c() {
        return 'own c';
    };
};
C.prototype.getRoles = function _getRoles() {
    return `The ${this.roles}-C.getRoles`;
};
const B = function _B(obj, roles) {
    C.call(this, roles);
    this.obj = obj;
    this.b = function _b() {
        return 'own b';
    };
};
// B.prototype = new C(); =>B.prototype.__proto__=C.prototype; So what happens? Both can be inherited
B.prototype = new C(); This. B inherits from B, this.c inherits from B, and this.c inherits from C
// B.prototype.__proto__=C.prototype; Same effect, but debug doesn't see if B and C inherit from other prototypes
B.prototype = new C();
B.prototype.constructor = B;
B.prototype.study = function _study() {
    return `The ${this.name}-B.study`;
};
const A = function _A(name, obj, roles) {
    B.call(this, obj, roles);
    this.name = name;
    this.play = function _play() {
        return `The ${this.name}-A.paly`;
    };
    this.b = function _bb() {
        return `The ${this.name}-a overrides method B;
    };
};
// A.prototype = new B(); =>A.prototype.__proto__=B.prototype; So what happens?
A.prototype = new B();
A.prototype.constructor = A;
A.prototype.getName = function _getName() {
    return this.name;
};
const a1 = new A('sweet', { age: 18},'Xu Fengnian']);
const a2 = new A('jade', { age: 18},'Wu Su']);
console.log(a1.play()); / / sweet potato - Amy polumbo aly
console.log(a2.play()); / / the bluebird - Amy polumbo aly
console.log(a1.getName()); / / sweet potato
console.log(a2.getName()); / / the bluebird
console.log(a1.study()); / / sweet potato - B.s tudy
console.log(a2.study()); / / the bluebird - B.s tudy
console.log(a1.getRoles()); // Xu Fengnian -C. G. etRoles
console.log(a2.getRoles()); / / be sad etRoles chtistina georgina rossetti.british poetess Wu Su -
console.log(a2 instanceof B); // true
console.log(a1 instanceof B); // true
console.log(a1 instanceof C); // true
console.log(a1 instanceof C); // true
console.log(a1.b()); // A overwrites b
console.log(a1.c()); / / c itself
console.log(a2.b()); // A overrides the b method
console.log(a2.c()); / / c itself

Copy the code

Constructor and __proto__ implementation inheritance

/* eslint-disable no-proto */
/** * @author: @description: Implement inheritance based on constructor and prototype chain. * /
// 1. A inherits B and B inherits C through the prototype chain and constructor
const C = function _C(roles = ['Xu Xiao'.'Wu Su'.'Tsui Chi Hu'.'Tsui Wei Xiong'.'Xu Fengnian'.'Xu Long Elephant']) {
    this.roles = roles;
    this.c = function _c() {
        return 'own c';
    };
};
C.prototype.getRoles = function _getRoles() {
    return `The ${this.roles}-C.getRoles`;
};
const B = function _B(obj, roles) {
    C.call(this, roles);
    this.obj = obj;
    this.b = function _b() {
        return 'own b';
    };
};
// B.prototype = new C(); =>B.prototype.__proto__=C.prototype; So what happens?
// B.prototype = new C(); Both C's own properties and methods and C. Stereotype methods are added to the stereotype chain. Identifies that B can inherit C's own methods and C's prototypical methods.
// B.prototype.__proto__=C.prototype; Methods on C stereotypes are added to the stereotype chain and cannot inherit C's own methods
B.prototype.__proto__ = C.prototype;
B.prototype.constructor = B;
B.prototype.study = function _study() {
    return `The ${this.name}-B.study`;
};
const A = function _A(name, obj, roles) {
    B.call(this, obj, roles);
    this.name = name;
    this.play = function _play() {
        return `The ${this.name}-A.paly`;
    };
    this.b = function _bb() {
        return `The ${this.name}-a overrides method B;
    };
};
// A.prototype = new B(); =>A.prototype.__proto__=B.prototype; So what happens?
A.prototype.__proto__ = B.prototype;
A.prototype.constructor = A;
A.prototype.getName = function _getName() {
    return this.name;
};
const a1 = new A('sweet', { age: 18},'Xu Fengnian']);
const a2 = new A('jade', { age: 18},'Wu Su']);
console.log(a1.play()); / / sweet potato - Amy polumbo aly
console.log(a2.play()); / / the bluebird - Amy polumbo aly
console.log(a1.getName()); / / sweet potato
console.log(a2.getName()); / / the bluebird
console.log(a1.study()); / / sweet potato - B.s tudy
console.log(a2.study()); / / the bluebird - B.s tudy
console.log(a1.getRoles()); // Xu Fengnian -C. G. etRoles
console.log(a2.getRoles()); / / be sad etRoles chtistina georgina rossetti.british poetess Wu Su -
console.log(a2 instanceof B); // true
console.log(a1 instanceof B); // true
console.log(a1 instanceof C); // true
console.log(a1 instanceof C); // true
console.log(a1.b()); // A overwrites b
console.log(a1.c()); / / c itself
console.log(a2.b()); // A overrides the b method
console.log(a2.c()); / / c itself

Copy the code

Parasitic composition implements inheritance

/* eslint-disable no-param-reassign */
/* eslint-disable no-proto */
/** * @author: @description: Implement inheritance based on constructor and prototype chain. * /
Call the parent constructor twice. To reduce memory consumption, use an empty intermediate object as a bridge.
const MyExtends = function _MyExtends(Son, Parent) {
    const F = function _F() {};
    const f = new F();
    f.__proto__ = Parent.prototype;
    Son.prototype = f;
    Son.prototype.constructor = Son;
};
const C = function _C(roles = ['Xu Xiao'.'Wu Su'.'Tsui Chi Hu'.'Tsui Wei Xiong'.'Xu Fengnian'.'Xu Long Elephant']) {
    this.roles = roles;
    this.c = function _c() {
        return 'own c';
    };
};
C.prototype.getRoles = function _getRoles() {
    return `The ${this.roles}-C.getRoles`;
};
const B = function _B(obj, roles) {
    C.call(this, roles);
    this.obj = obj;
    this.b = function _b() {
        return 'own b';
    };
};
MyExtends(B, C);
B.prototype.study = function _study() {
    return `The ${this.name}-B.study`;
};
const A = function _A(name, obj, roles) {
    B.call(this, obj, roles);
    this.name = name;
    this.play = function _play() {
        return `The ${this.name}-A.paly`;
    };
    this.b = function _bb() {
        return `The ${this.name}-a overrides method B;
    };
};
// A.prototype = new B(); =>A.prototype.__proto__=B.prototype; So what happens?
MyExtends(A, B);
A.prototype.getName = function _getName() {
    return this.name;
};
const a1 = new A('sweet', { age: 18},'Xu Fengnian']);
const a2 = new A('jade', { age: 18},'Wu Su']);
console.log(a1.play()); / / sweet potato - Amy polumbo aly
console.log(a2.play()); / / the bluebird - Amy polumbo aly
console.log(a1.getName()); / / sweet potato
console.log(a2.getName()); / / the bluebird
console.log(a1.study()); / / sweet potato - B.s tudy
console.log(a2.study()); / / the bluebird - B.s tudy
console.log(a1.getRoles()); // Xu Fengnian -C. G. etRoles
console.log(a2.getRoles()); / / be sad etRoles chtistina georgina rossetti.british poetess Wu Su -
console.log(a2 instanceof B); // true
console.log(a1 instanceof B); // true
console.log(a1 instanceof C); // true
console.log(a1 instanceof C); // true
console.log(a1.b()); // A overwrites b
console.log(a1.c()); / / c itself
console.log(a2.b()); // A overrides the b method
console.log(a2.c()); / / c itself

Copy the code

deconstruction

/** * @author: @description:ES6 allows extracting values from arrays and objects and assigning values to variables in a pattern called Destructuring. * /
// 1. Array structure assignment
const [a, b, c, d, e = 6] = [1.2.3];
console.log(a); / / 1
console.log(b); / / 2
console.log(c); / / 3
console.log(d); // undefined
console.log(e); / / 6
// 2. Assign the structure of the object
// Linfei, have you found ganlinzhen in Datang
const { bar, foo } = { foo: 'linfei'.bar: 'Ganzen' };
console.log(bar);
console.log(foo);
// 3. String structure
const [a1, b1, c1, d1] = 'abcd';
console.log(a1); // a
console.log(b1); // b
console.log(c1); // c
console.log(d1); // d
const arr = [...'abcd'];
console.log(arr); // [ 'a', 'b', 'c', 'd' ]
// 4. Function parameter assignment
const func = function _func({ x, y }) {
    console.log(`x:${x}`); // x:1
    console.log(`y:${y}`); // y:2
    return x + y;
};
console.log(func({ x: 1.y: 2 })); / / 3

Copy the code

this

The resources

Hey, do you really understand this?

/** * @author: Zhang Panqin * This article is based on Liu Xiaoxi's blog [Hi, do you really understand this? (https://juejin.cn/post/6844903805587619854). * @description: The function this refers to when the execution context is pushed up or down. This refers to the calling context */
// 1. Default binding, pointing to global functions.
const f1 = function _f1() {
    if (this === global) {
        console.log('This points to a global object');
    } else {
        console.log(this); }};// The global context calls the function f1, so this points to global
f1();
// implicit binding
const f2 = function _f2() {
    if (this === global) {
        console.log('This points to a global object');
    } else {
        console.log(this); }};const obj = { age: 10.f: f2 };
// Run the function in the execution context of obj
obj.f(); // { age: 10, f: [Function: _f2] }
const f3 = obj.f;
The global execution context executes the function f3, which points to global
f3(); // This points to the global object
/ / 3. Display binding Function. The prototype. The call of the Function. The prototype. The apply of the Function. The prototype. The bind
// 4. New, initialize the object, bind this to the object
Copy the code

arrow-this

/** * @description: Confirmation of arrow function this * this in arrow function inherits function from outer library */
global.name = 'global';
const obj = {
    name: 'obj',
    hi() {
        return (a)= > {
            console.log(this.name);
        };
    },
    hiFunction() {
        return function _f() {
            console.log(this.name);
        };
    },
    say: (a)= > {
        console.log(this.name);
    },
    sayFunction() {
        console.log(this.name); }};const ret = obj.hi();
ret(); // obj
const retFunction = obj.hiFunction();
retFunction(); // global
obj.say(); // undefined
const objFunction = obj.say;
objFunction(); // undefined
obj.sayFunction(); // obj
const { sayFunction } = obj;
sayFunction(); // global

Copy the code