当前位置:网站首页>ES6 summary
ES6 summary
2022-07-04 08:12:00 【yibucuo】
Basic data type
- Numbers 、 character string 、 Boolean 、symbol、bigInt、undefined、null
- object
Set usage
It's like an array , But the values of the members are unique , There are no duplicate values .
Only NaN and === Dissimilarity Everything else is the same
var set = new Set(NaN)
set.add(NaN);
set // Set {NaN}
set.size //1
set.delete() // Delete a value The return value indicates whether the deletion is successful
set.has() // Returns a Boolean value Indicates whether there is a value
set.clear() // Clear all items no return value
[...new Set('ababbc')] // ['a','b','c']
You can also use Array.from Untie Set example
let set = new Set(['red', 'green', 'blue']);
for (let item of set.keys()) {
console.log(item);}// red green blue
for (let item of set.values()) {
console.log(item);}// red green blue
for (let item of set.entries()) {
console.log(item);}// ["red", "red"] ["green", "green"] ["blue", "blue"]
Set.prototype[Symbol.iterator] === Set.prototype.values // true So it can be used for...of Loop to get each value
for (let i of set) {
console.log(i);// obtain set Every item inside
}
set.forEach((value, key) => console.log(key + ' : ' + value)) // key and value Have the same value
You can put Set Instances are treated as arrays Conduct map and filter operation Similar to array usage
const p = [item,item,...] // item It must be an object or an array Otherwise, the report will be wrong
const set = new WeakSet(b);
set.add(value)
set.delete(value)
set.has(value)
set.size // undefined No, size and forEach
set.forEach // undefined
Map usage
DOM Nodes as objects data Key , But because objects only accept strings as key names , therefore element Is automatically converted to a string [object HTMLDivElement].
const data = {
};
const element = document.getElementById('myDiv');
data[element] = 'metadata';
data['[object HTMLDivElement]'] // "metadata"
To solve this problem ,ES6 Provides Map data structure . It's like an object
var obj = {
}
var map = new Map([
[obj, '111'],
['key2', '222']
]);
map.get(obj) //111
// There are these ways has get set delete clear size forEach keys values entries
for...map.keys() => The first is obj You can also use [...map.keys()]
for...map.values() => The first is "111" You can also use [...map.values()]
for...map.entries() => The first is [obj,'111'] You can also use [...map.entries()]
for...map.forEach(value, key) => The first one is value by '111' key by obj
WeakMap Only objects are accepted as key names
WeakMap In the face element Is a weak reference , Will not be included in the garbage collection mechanism .
These are the only ways has get set delete
const wm1 = new WeakMap();
Promise
// Ask for sth table data
function requestTableList(){
var p = new Promise((resolve, reject) => {
// Go to the background to request data , This could be ajax, It can be axios, It can be fetch
resolve(res);
});
return p;
}
// The time delay function , Used to time requests 10s
function timeout(){
var p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(' request timeout ');
}, 10000);
});
return p;
}
Promise.race([requestTableList(), timeout()]).then((data) =>{
// Successful callback processing
console.log(data);
}).catch((err) => {
// Failed callback processing
console.log(err);
});
function promiseClick1(){
let p = new Promise(function(resolve, reject){
setTimeout(function(){
var num = Math.ceil(Math.random()*20); // Generate 1-10 The random number
console.log(' Values generated by random numbers :',num)
if(num<=10){
resolve(num);
}
else{
reject(' Number too much 10 About to execute the failed callback ');
}
}, 2000);
})
return p
}
function promiseClick2(){
let p = new Promise(function(resolve, reject){
setTimeout(function(){
var num = Math.ceil(Math.random()*20); // Generate 1-10 The random number
console.log(' Values generated by random numbers :',num)
if(num<=10){
resolve(num);
}
else{
reject(' Number too much 10 About to execute the failed callback ');
}
}, 2000);
})
return p
}
function promiseClick3(){
let p = new Promise(function(resolve, reject){
setTimeout(function(){
var num = Math.ceil(Math.random()*20); // Generate 1-10 The random number
console.log(' Values generated by random numbers :',num)
if(num<=10){
resolve(num);
}
else{
reject(' Number too much 10 About to execute the failed callback ');
}
}, 2000);
})
return p
}
Promise
.all([promiseClick3(), promiseClick2(), promiseClick1()])
.then(function(results){
console.log(results);
})
class Inherit
Parent is superclass Children are subclasses Subclasses inherit superclasses call super In fact, it calls the constructor method of the superclass
class A {
constructor(a) {
this.a = a;
}
}
class B extends A {
constructor(a, b) {
super(a);
this.b = b;
}
}
class C extends B {
constructor(a, b, c) {
super(a, b);
this.c = c;
}
}
console.log(new C(1, 2, 3))//C { a: 1, b: 2, c: 3 }
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-1K66PnzH-1656645685958)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3eda935987e44040b5f12a095e093bb7~tplv-k3u1fbpfcp-zoom-1.image)]
Promise Parallel and serial , as well as await Underlying implementation
Premise code
var query = function (value) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(value)
}, value)
})
}
parallel Mode one 1 Second output 1000, In another 1 A second output 2000, In another 1 A second output 3000
query(1000).then(v => {
console.log(v)
})
query(2000).then(v => {
console.log(v)
})
query(3000).then(v => {
console.log(v)
})
parallel Mode two Output in three seconds [1000, 2000, 3000]
Promise.all([query(1000),query(2000),query(3000)]).then(v=>{
console.log(v)
})
Serial Mode one Output is 1 Second output 1000, In another 2 A second output 2000, In another 3 A second output 3000
query(1000).then(v => {
console.log(v)
return query(2000)
}).then(v => {
console.log(v)
return query(3000)
}).then(v => {
console.log(v)
})
Serial Mode two Output is 1 Second output 1000, In another 2 A second output 2000, In another 3 A second output 3000
let itor = generator()
itor.next().value.then(value => {
itor.next(value).value.then(value => {
itor.next(value).value.then(value => {
itor.next(value)
})
})
})
await Underlying implementation
const isPromise = function (v) {
if (v !== null && /^(object|function)$/i.test(typeof v)) {
let then;
try {
then = x.then
} catch (err) {
return false
}
if (typeof then === 'function') return true
}
return false
}
function AsyncFunction(generator, ...params) {
return new Promise((resolve, reject) => {
let itor = generator(...params);
const next = v => {
let {
value,
done
} = itor.next(v)
if (done) {
resolve(value)
return
}
if (!isPromise(value)) value = Promise.resolve(value)
value.then(v => {
next(v)
}).catch(reason => {
reject(reason)
itor.throw(reason)
})
}
next()
})
}
AsyncFunction(function* generator() {
let value;
y1 = yield query(1000)
console.log(y1)
y2 = yield query(2000)
console.log(y2)
y3 = yield query(3000)
console.log(y3)
return 'zanlan'
}).then(v => {
console.log(' All requests were successful ', v)
}).catch(reason => {
console.log(' A request failed ', reason)
})
General function implementation
/* Real projects be based on async/awai Can be implemented directly */
/* We are based on promise + generator + AsyncFunction function , What is achieved is async/await Processing mechanism */
/* async/awai yes promise + generator The grammar sugar of */
(async function () {
let value;
try {
value = await Promise.reject('xxx')
console.log(' The first request succeeded ', value)
} catch (err) {
console.log(err)
}
value = await query(2000)
console.log(' The second request succeeded ', value)
value = await query(3000)
console.log(' The third request succeeded ', value)
})()
generator principle
Execute a function as an ordinary function , Whether you can create an instance of this class ?
jquery.fn() // Factory design mode Realization
function* fn() {
// generator Realization ,itor yes fn Instance object of fn Internal code not executed
console.log(this)
return 10
}
let itor = fn()
console.log(itor)
Output window, At output { value:10 , done:true }
function* fn() {
console.log(this)
return 10
}
let itor = fn()
console.log(itor.next())
Output as follows
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-CghJhoeC-1656645685966)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2fabd05724794427a96733e4f03229c2~tplv-k3u1fbpfcp-zoom-1.image)]
function* generator() {
console.log(1)
yield 2
console.log(3)
yield 4
console.log(5)
yield 6
console.log(7)
return 8
}
let itor = generator()
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
Output as follows
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-KdJYJRJQ-1656645685968)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/14d36e9a5602412f960b520747896c65~tplv-k3u1fbpfcp-zoom-1.image)]
function* generator() {
console.log(1)
let y2 = yield 2
console.log(y2)
console.log(3)
let y4 = yield 4
console.log(y4)
console.log(5)
let y6 = yield 6
console.log(y6)
console.log(7)
return 8
}
let itor = generator()
console.log(itor.next('aa'))
console.log(itor.next('bb'))
console.log(itor.next('cc'))
console.log(itor.next('dd'))
Output is as follows
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-8zIlIQvg-1656645685970)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/491da2d576424606bc08c302903c3d14~tplv-k3u1fbpfcp-zoom-1.image)]
function* generator1() {
yield 2;
yield 3;
return 4
}
function* generator2() {
yield 1;
yield* generator1();
yield 5;
return 6;
}
let itor = generator2();
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
Iterator Source code
class Iterator {
constructor(assemble) {
let self = this;
self.assemble = assemble;
self.index = 0;
}
next() {
let self = this;
let assemble = self.assemble;
if (self.index > assemble.length - 1) {
return {
done: true,
value: undefined
}
}
return {
done: false,
value: assemble[self.index++]
}
}
}
General application
let itor = new Iterator([10, 20, 30, 40])
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
The following code can make general objects use for of loop
Object.prototype[Symbol.iterator] = function () {
let self = this
let keys = Object.keys(self).concat(Object.getOwnPropertySymbols(self))
let index = 0
return {
next() {
if (keys.length - 1 < index) {
return {
done: true,
value: undefined
}
}
return {
value: self[keys[index++]],
done: false
}
}
}
}
For class array , Then directly borrow the Symbol.iterator function
var obj = {
0: 'a',
1: 'b',
length: 2
}
obj[Symbol.iterator] = Array.prototype[Symbol.iterator]
for (var value of obj) {
console.log(value)
}
jquery Is an array of classes , Here is jquery The source code to achieve
jQuery.fn[Symbol.iterator] = [][Symbol.iterator];
async && await Interview questions
Two functions are known , Ask questions separately , The results of
var f1 = function f1() {
console.log(1)
return new Promise(resolve => {
setTimeout(() => {
resolve(6)
console.log(5)
}, 2000);
})
}
var f2 = function f2() {
console.log(2)
return new Promise(resolve => {
setTimeout(() => {
resolve(4)
console.log(3)
}, 1000);
})
}
problem 1 The output is :1 5 6 2 3 4
var f = async function () {
console.log(await f1())
console.log(await f2())
}
f()
problem 2 The output is :1 2 3 5
Promise.all([
f1(),
f2(),
])
problem 3 The output is :1 2 3 4 5 6
Promise.all([
(async () => {
console.log(await f1()) })(),
(async () => {
console.log(await f2()) })(),
])
class Inherit
Parent is superclass Children are subclasses Subclasses inherit superclasses call super In fact, it calls the constructor method of the superclass
class A {
constructor(a) {
this.a = a;
}
}
class B extends A {
constructor(a, b) {
super(a);
this.b = b;
}
}
class C extends B {
constructor(a, b, c) {
super(a, b);
this.c = c;
}
}
console.log(new C(1, 2, 3))//C { a: 1, b: 2, c: 3 }
ES5 and ES6 Modular import and export of
// Do not receive objects
require:require('s.css'); //(es5)
improt 's.css' //(es6)
// The recipient
var o = require('s.js'); //es(5)
import o form s.js //(es6)
Export a module object (es5):
module.exports={
add:add,
sub:sub
}
Export a module object (es6):
module.exports={
add,
sub
}
Be careful : In this way, the attribute name and the attribute value variable are the same , Otherwise, write separately
module.exprots={
addFn:add,
sub
}
//es5
module.exports={
addFun:function(x,y){
return x+y;
}
}
//es6
module.exports={
addFun(x,y){
return x+y;
}
}
calc.js There are two functions in :
function add(){
}
function sub(){
}
// Writing a
es5 How to write it :
module.exports.add = add;
module.exports.sub = sub;
Use :
var calc = require('./calc.js');
es6 How to write it :
exprot function add(){
}
exprot function sub(){
}
// Write two
es5:
module.exports = {
add:add,sub:sub};
es6:
exprot default{
add,sub
}
// It means to obtain calc.js All exposed objects in (es6)
import calc from './calc.js'
// Only get calc.js Medium add Method ( Acquisition on demand )
import {
add} from './calc.js'
1、 If... Is used in the module export default {
} Method to export objects
Only through import Object name from ' The module path '
Cannot pass import {
Object name } from ' The module path '
2、 If you want import {
Object name } from ' The module path ' In this way, you can import a property in the object on demand
So you should use export Followed by the name of the object or method to be exported
export function add(){
}
export function substrct(){
}
Then you can use it :
import {
add,substrct} from ' The module path '
Just use... Directly add() The method can
Note that you can't use it directly here : import cacl from ' The module path ' This way, import , Will report a mistake
class Inherit
```typescript
Parent is superclass Children are subclasses Subclasses inherit superclasses call super In fact, it calls the constructor method of the superclass
class A {
constructor(a) {
this.a = a;
}
}
class B extends A {
constructor(a, b) {
super(a);
this.b = b;
}
}
class C extends B {
constructor(a, b, c) {
super(a, b);
this.c = c;
}
}
console.log(new C(1, 2, 3))//C { a: 1, b: 2, c: 3 }
ES5 and ES6 And Object Used methods
es6 Of prototype You can't enumerate
class Person {
constructor(x, y) {
}
toString() {
}
}
console.log(Object.keys(Person.prototype)); //[]
console.log(Object.getOwnPropertyNames(Person.prototype)); //["constructor", "toString"]
function Person1() {
}
Person1.prototype.toString = function () {
};
console.log(Object.keys(Person1.prototype)); //["toString"]
console.log(Object.getOwnPropertyNames(Person1.prototype)); //["constructor", "toString"]
Automatic addition constructor function
class Person {
}
etc. price
class Person {
constructor(x, y) {
}
}
constructor Default return Instantiate objects this, But you can customize
class The function must new To call ,es5 Unwanted new You can also call
class Foo{
constructor(){
return Object.create(null);
}
}
new Foo() instanceof Foo //false
Modify an instance __proto__ Methods , Other examples will also be implicated
class Person {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return this.x + '--' + this.y;
}
}
let p = new Person(1, 2);
console.log(p.hasOwnProperty('x')); //true
console.log(p.hasOwnProperty('y')); //true
console.log(p.hasOwnProperty('constructor')); //false
console.log(p.hasOwnProperty('toString')); //false
console.log(p.__proto__.hasOwnProperty('constructor')); //true
console.log(p.__proto__.hasOwnProperty('toString')); //true
let p1 = new Person(2, 3);
p1.__proto__.toString = function () {
return 'what fuck?';
};
let p2 = new Person(3, 4);
console.log(p1.toString());//what fuck?
console.log(p2.toString());//what fuck?
class You can customize variables ,Person Only valid inside the constructor , and clafun Is used for external calls
let clafun = class Person {
constructor(x, y) {
this.x = x;
}
toString() {
return this.x + '--' + Person.name;
}
};
let p = new clafun(1);
console.log(p.toString());//1--Person
// var p1 = new Person(1);//Person is not defined
// If you don't use clafun It can be abbreviated as
// If you don't use clafun It can be abbreviated as
let p = new class Person {
constructor(x, y) {
this.x = x;
}
toString() {
return this.x + '--' + Person.name;
}
}(1);
console.log(p.toString());//1--Person
// var p1 = new Person(1);//Person is not defined
class No variable promotion ,let No variable promotion , hypothesis class There is variable promotion , Is an error Foo yes undefined , In fact, there is no error , explain class No variable promotion
{
let Foo=class {
};
class Bar extends Foo{
}
}
this Direction problem of , By default, it points to the instantiated object , But through the method of deconstruction , Then inside the function this It points to the environment because es6 The default is in strict mode , So it points to undefined, There are three solutions
- bind change this The direction of
- Arrow function
- proxy
console.log(this); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
class Person {
constructor() {
// this.fun1 = this.fun1.bind(this); // Method 1
// this.fun1 = () => {
// // Method 2
// return this.fun2() + '-------------';
// };
}
fun1() {
console.log(this); // The instantiation call points to instantiation Deconstruction points to the environment ,es6 The default is strict mode , So for undefined
return this.fun2() + '--------';
}
fun2() {
return 'what';
}
}
let p = new Person();
console.log(p.fun1()); //what--------
const {
fun1 } = p;
console.log(fun1()); //fun1 Inside this Point to the running environment Cannot read property 'fun2' of undefined
proxy add to this
function selfish(target) {
const cache = new WeakMap();
const handler = {
get(target, key) {
const value = Reflect.get(target, key);
if (typeof value !== 'function') {
return value;
}
if (!cache.has(value)) {
cache.set(value, value.bind(target));
}
return cache.get(value);
},
};
const proxy = new Proxy(target, handler);
return proxy;
}
const p = selfish(new Person());
class Inherit static Method es6 Only static methods have no static properties
class Foo {
static fun1() {
return '111';
}
}
class Bar extends Foo {
static fun2() {
return super.fun1() + '222';
}
}
console.log(Bar.fun1());//111
console.log(Bar.fun2());//111222
class Declare instantiated properties and methods
class Foo {
constructor() {
this.state1 = {
};
}
state = {
name: 1 };
fun1() {
return 11111;
}
}
console.log(new Foo().hasOwnProperty('state1')); //true
console.log(new Foo().hasOwnProperty('state')); //true
console.log(new Foo().__proto__.hasOwnProperty('fun1')); //true
ES5 and ES6 Of get and set Comparison of methods
ES5
var obj = {
};
Object.defineProperty(obj, 'name', {
get: function () {
console.log(' Visiting name');
return this._name;
},
set: function (val) {
console.log(' Modifying name');
this._name = val;
},
});
obj.name = 10;
console.log(obj);
console.log(obj.name);
// Modifying name
// { _name: 10 }
// Visiting name
// 10
ES6
class Person{
constructor(){
this._name = '';
}
get name(){
console.log(" Visiting name attribute ");
return ` My name is ${
this._name}`;
}
set name(val){
console.log(" Modifying name attribute ");
this._name = val;
}
}
const person = new Person();
person.name = " Dema - Compress ";
console.log(person.name); // First visit set Revisit get
// Modifying name
// Visiting name
// My name is dema - Compress
es7
let a = 7 ** 12
let b = 2 ** 7
console.log(a === Math.pow(7,12)) // true 7 Of 12 Power
console.log(b === Math.pow(2,7))
边栏推荐
- Relations courantes de la fiche de données d'exploitation pour les activités
- Li Kou today's question -1200 Minimum absolute difference
- L1-023 output gplt (20 points)
- Project 1 household accounting software (goal + demand description + code explanation + basic fund and revenue and expenditure details record + realization of keyboard access)
- [gurobi] establishment of simple model
- Devops Practice Guide - reading notes (long text alarm)
- Application of isnull in database query
- 1. Qt入门
- 一文了解數據异常值檢測方法
- The second session of the question swiping and punching activity -- solving the switching problem with recursion as the background (I)
猜你喜欢
Preliminary study on temporal database incluxdb 2.2
Redis sentinel mechanism
Azure ad domain service (II) configure azure file share disk sharing for machines in the domain service
zabbix監控系統自定義監控內容
Comparison between applet framework and platform compilation
What are the work contents of operation and maintenance engineers? Can you list it in detail?
zabbix监控系统邮件报警配置
Flask 常用组件
Comprendre la méthode de détection des valeurs aberrantes des données
Take you to master the formatter of visual studio code
随机推荐
Practice (9-12 Lectures)
论文学习——基于极值点特征的时间序列相似性查询方法
Leetcode 146. LRU 缓存
Do you know about autorl in intensive learning? A summary of articles written by more than ten scholars including Oxford University and Google
Unity-写入Word
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
Need help resetting PHP counters - PHP
Li Kou today's question -1200 Minimum absolute difference
真空介电常数和真空磁导率究竟是由什么决定的?为何会存在这两个物理量?
L1-028 judging prime number (10 points)
JVM中堆概念
The right way to capture assertion failures in NUnit - C #
How to send mail with Jianmu Ci
This monitoring system can monitor the turnover intention and fishing all, and the product page has 404 after the dispute appears
Azure ad domain service (II) configure azure file share disk sharing for machines in the domain service
ZABBIX monitoring system custom monitoring content
Easy to understand: understand the time series database incluxdb
Tri des fonctions de traitement de texte dans MySQL, recherche rapide préférée
OKR vs. KPI figure out these two concepts at once!
R language ggplot2 visualization: ggplot2 visualization grouping box diagram, place the legend and title of the visualization image on the top left of the image and align them to the left, in which th