ES6
1. Let variable declarations and declaration features
1.1 Variables cannot be declared twice
let star = 'Lo Zhixiang'
let star = 'pig' / / an error
Copy the code
1.2 block-level scoped global, functions, eval
//if else while for
{
let girl = 'Fan Bingbing'
}
console.log(girl) / / an error
Copy the code
1.3 There is no variable promotion
console.log(song) / / an error
let song = 'In love'
Copy the code
1.4 Does not affect the scope chain
{
let school = 'the north'
function fn(){
console.log(school)
}
fn()
}
Copy the code
Let classic example: iterate over binding events
for(let i=0; i<items.length; i++){ items[i].onclick =function(){
//this.style.background = 'pink'
items[i].style.background = 'pink'}}Copy the code
2. Constant declaration and declaration characteristics
2.1 Declaring Constants
const school = 'the north'
Copy the code
2.2 Be sure to assign an initial value
const A / / an error
Copy the code
2.3 Uppercase for General Constants (Unspoken Rule)
const a = 100
Copy the code
2.4 Constant values cannot be modified
school = 'beida' / / an error
Copy the code
2.5 block-level scope
{
const PLAYER = 'UZI'
}
console.log(PLAYER) / / an error
Copy the code
2.6 Element modification of arrays and objects is not considered as constant modification, and no error will be reported
const TEAM = ['UZI'.'MXLG'.'Ming'.'Letme']
TEAM.push('Meiko')
Copy the code
3. Deconstructive assignment of variables
Deconstructing Assignment: ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern
3.1 Array deconstruction
const F4 = ['Little Shenyang'.'liu can'.'zhao four'.'Song Xiaobao']
let [xiao, liu, zhao, song] = F4
console.log(xiao)
console.log(liu)
console.log(zhao)
console.log(song)
Copy the code
3.2 Object deconstruction
const zhao = {
name: 'Zhao Benshan'.age: 'not'.xiaopin: function(){
console.log('I can do skits.')}}// Objects are destructed with curly braces
let {name, age, xiaopin} = zhao
console.log(name)
console.log(age)
console.log(xiaopin)
xiaopin()
Copy the code
3.3 If the deconstruction fails, the value of the variable is equal to undefined
let [foo] = []
let [bar, foo] = [1]
// In both cases, the deconstruction fails, and the value of foo equals undefined
Copy the code
4. Template string
ES6 introduces new ways of declaring strings.
4.1 the statement
let str = 'I'm a string too! `
console.log(str,typeof str)
Copy the code
4.2 Newline characters can appear directly in content
let str = '
- Shen Teng
< Li > Mary
- Alan
'
Copy the code
4.3 Variable Splicing (Common)
let lovest = 'wei zifeng'
let out = `${lovest}The funniest actor!! `
console.log(out)
Copy the code
5. Simplify object writing
ES6 allows variables and functions to be written directly inside curly braces as object properties and methods
let name = 'the north'
let change = function(){
console.log('The highest institution! ')}const school = {
name,
change,
// A simplified version of the method
impove(){
console.log('Improve your skills')}}Copy the code
Arrow function
ES6 allows functions to be defined using [arrow] (=>)
// Declare a function
//let fn =function(){
//
/ /}
let fn = (a,b) = > {
return a+b
}
// Call the function
let result= fn(1.2)
console.log(result) / / 3
Copy the code
6.1 This is static. This always refers to the value of this in the scope in which the function was declared
function getName(){
console.log(this.name)
}
let getName2 = () = > {
console.log(this.name)
}
// Sets the name attribute of the window object
window.name = 'the north'
const school = {
name: 'tsinghua'
}
// Call directly
getName() / / the north
getName2() / / the north
//call method call
getName.call(school) / / tsinghua
getName2.call(school) / / the north
Copy the code
6.2 Objects cannot be instantiated as constructors
let Person = (name, age) = > {
this.name = name
this.age = age
}
let me = new Person('xiao'.17)
console.log(me) / / an error
Copy the code
6.3 Arguments variables cannot be used
let fn = () = >{
console.log(arguments)
}
fn(1.2.3) / / an error
Copy the code
6.4 Short for arrow function
//1) omit the parentheses when the parameter has one and only one
let add = n= > {
return n + n
}
console.log(add(9)) / / 18
//2) omit the curly braces. Return must be omitted when the code body contains only one statement
// The result of the statement is the return value of the function
let pow = n= > n * n
console.log(pow(8)) / / 64
Copy the code
6.5 Arrow function practice
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Arrow function practice</title>
<style>
div {
width: 200px;
height: 200px;
background: #58a;
}
</style>
</head>
<body>
<div id="ad"></div>
<script>
// requirement -1 when I click div 2s, the color becomes pink
let ad = document.getElementById('ad')
ad.addEventListener('click'.function(){
// Save this
// let _this = this
/ / timer
setTimeout(() = > {
// Change the background color this
// console.log(this)
// _this.style.background = 'pink'
this.style.background = 'pink' / / this point to the AD
}, 2000)})// Requirement -2 returns an even number of elements from the array
const arr = [1.6.9.10.100.25]
// const result = arr.filter(function(item){
// if(item%2 === 0){
// return true
// }else{
// return false
/ /}
// })
const result = arr.filter(item= > item%2= = =0)
console.log(result)
// The arrow function is suitable for callbacks unrelated to this. Timer, array method callback
// Arrow functions are not suitable for callbacks related to this. Event callback, method of the object
</script>
</body>
</html>
Copy the code
7. Default values of function parameters
ES6 allows assigning initial values to function arguments
7.1 Parameter Initial Value Parameter with default value, usually placed later (unspoken rule)
function add(a,b,c=10){
return a+b+c
}
let result = add(1.2)
console.log(result) / / 13
Copy the code
7.2 Combined with deconstruction assignment
function connect({host='127.0.0.1', username, password, port}){
console.log(host)
console.log(username)
console.log(password)
console.log(port)
}
connect({
host: 'localhost'.username: 'root'.password: 'root'.port: '3306'
})
Copy the code
8. The rest parameters
ES6 introduces the rest argument, which gets arguments to functions, instead of arguments
ES5 How to get arguments
function date(){
console.log(arguments)
}
date('cheung'.'other'."Sophia")
Copy the code
Rest arguments must be placed last or an error will be reported
function date(. args){
console.log(args) // Use the filter some every map method
}
date('cheung'.'other'."Sophia")
Copy the code
9. Extend operators
[…]. Extended operators convert [array] to comma-separated [sequence of arguments]
const tfboys = [Jackson Yi.'hanah'.'Wang Junkai']
function chunwan(){
console.log(arguments) } chunwan(... tfboys)// Chuanwan (' Yi Yangqianxi ',' Wang Yuan ',' Wang Junkai ')
Copy the code
Extend operator application
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Extend operator application</title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
//1. Array merge
const kuaizi = ['Wang Taili'."Xiao"]
const fenghuang = ['chenrui'.'ling flowers']
// const zuixuanxiaopingguo = kuaizi.concat(fenghuang)
const zuixuanxiaopingguo = [...kuaizi,...fenghuang]
console.log(zuixuanxiaopingguo)
//2. Clone the shallow copy of the array
const sanzhihua = ['E'.'G'.'M']
const sanyecao = [...sanzhihua]
console.log(sanyecao)
//3. Convert the pseudo-array to a real array
const divs = document.querySelectorAll('div')
const divArr = [...divs]
console.log(divArr)
</script>
</body>
</html>
Copy the code
10.Symbol
10.1 ES6 introduces a new primitive data type, Symbol, which represents unique values.
It is the seventh data type of the JavaScript language and is a string-like data type. Symbol features 1) The value of Symbol is unique and is used to resolve naming conflicts. 2) The value of Symbol cannot be computed with other data. 3) The object attributes defined by Symbol cannot be used for.. In loops through, but you can use reflect.ownkeys to get all the key names of the object
/ / create a Symbol
let s = Symbol(a)//console.log(s,typeof s)
let s2 = Symbol('the north')
let s3 = Symbol('the north')
console.log(s2 === s3) //false
/ / Symbol. For creation
let s4 = Symbol.for('the north')
let s5 = Symbol.for('the north')
console.log(s4 === s5) //true
// Cannot be computed with other data
//let result = s + 100
//let result = s > 100
//let result = s + s
//js 7 raw data types
//u undefined
//s string symbol
//o object
//n number null
//b boolean
Copy the code
10.2 Symbol Creates object properties
// Add the method up down to the object
let gane = {
name: tetris.up: function(){},
down: function(){}}// Declare an object
//let methods = {
// up: Symbol(),
// down: Symbol()
/ /}
//game[method.up] = function(){
// console.log(' Change shape ')
/ /}
//game[method.down] = function(){
// console.log(' fast drop ')
/ /}
let youxi = {
name: 'Werewolf Kill'[Symbol('say')]: function(){
console.log('speak')},Symbol('zibao')]: function(){
console.log('explosive')}}console.log(youxi)
Copy the code
10.3 Symbol Built-in attribute
class Person{
static [Symbol.hasInstance](param){
console.log(param)
console.log('I'm being used to detect types.')
return false}}let o = {}
console.log(o instanceof Person) //
const arr = [1.2.3]
const arr2 = [4.5.6]
arr2[Symbol.isConcatSpreadable] = false / / no
console.log(arr.concat(arr2)) / / [1, 2, 3, Array (3)]
Copy the code
11 Iterator Iterator
11.1 An Iterator is an interface that provides a unified access mechanism for a variety of different data structures. Any data structure can be iterated by deploying the Iterator interface.
- ES6 created a new traversal command for… The of loop is an Iterator interface for… Of consumption
A) Array B) Arguments C) Set D) Map E) String f) TypedArray g) NodeList
3) How it works a) Create a pointer object that points to the starting position of the current data structure b) Call next and the pointer automatically points to the first member of the data structure c) call next repeatedly and the pointer moves backwards. D) Each call to next returns an object containing the value and done attributes. Note: When you need to customize traversal data, think of iterators.
// Declare an array
const xiyou = ["Tang's monk.Sun Wukong.'Pig Eight Quit'.'沙僧']
/ / used for... Of keys /for... In traversal key name
for(let v of xiyou){
console.log(v)
}
let iterator = xiyou[Symbol.iterator]()
// Call the next method of the object
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
Copy the code
11.2 Customizing Traversal Data
// Declare an object
const banji = {
name: 'Terminal Class'.stus: [
'xiaoming'.'xiaotian'.'xiaodong'.'xiaonan'
],
[Symbol.iterator](){
// Index variable
let index = 0
/ / save this
let _this = this
return {
next: function(){
if(index < _this.stus.length){
const result = { value: _this.stus[index],done: false}
// subscript increment
index++
return result
}else{
return {value: undefined.done: true}
}
}
}
}
}
// Iterate over the object
for(let v for banji){
console.log(v)
}
Copy the code
12. The generator
12.1 Generator functions are ES6’s easy asynchronous programming solutions with completely different syntactic behavior from traditional functions
// A generator function is a special function
// Asynchronous programming pure callback functions
// Yield the delimiter of the function code
function * gen(){
//console.log('111')
yield 'One without an ear'
//console.log('222')
yield 'One without a tail'
//console.log('333')
yield 'That's strange'
//console.log('444')
}
let iterator = gen()
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
/ / traverse
//for(let v of gen()){
// console.log(v)
/ /}
Copy the code
12.2 Generator function parameter passing
function * gen(arg){
console.log(arg)
let one = yield 111
console.log(one) //BBB
let two = yield 222
console.log(two) //CCC
let three = yield 333
console.log(three) //DDD
}
let iterator = gen('AAA')
console.log(iterator.next())
// The next method can take arguments
console.log(iterator.next('BBB')) // The argument passed is returned as the result of the first yeild
console.log(iterator.next('CCC')) // The argument passed is returned as the result of the second yeild
console.log(iterator.next('DDD')) // The argument passed is returned as the result of the third yeild
Copy the code
12.3 Examples of generator functions
// Asynchronous programming file operations network operations (Ajax,request) database operations
// Console output 111 after 1s, 222 after 2s, 333 after 3s
// Call back to hell
setTimeout(() = >{
console.log(111)
setTimeout(() = >{
console.log(222)
setTimeout(() = >{
console.log(333)},3000)},2000)},1000)
function one(){
setTimeout(() = >{
console.log(111)
iterator.next()
},1000)}function two(){
setTimeout(() = >{
console.log(222)
iterator.next()
},2000)}function three(){
setTimeout(() = >{
console.log(333)
iterator.next()
},3000)}function * gen(){
yield one()
yield two()
yield three()
}
let iterator = gen()
iterator.next()
Copy the code
// Get user data, order data, commodity data
function getUsers() {
setTimeout(() = >{
let data = 'User data'
// Call the next method and pass in the data
iterator.next(data)
},1000)}function getOrders() {
setTimeout(() = >{
let data = 'Order data'
// Call the next method and pass in the data
iterator.next(data)
},1000)}function getGoods() {
setTimeout(() = >{
let data = 'Commodity data'
// Call the next method and pass in the data
iterator.next(data)
},1000)}function * gen(){
let users = yield getUsers()
let orders = yield getOrders()
let goods = yield getGoods()
}
let iterator = gen()
iterator.next()
Copy the code
13.Promise
13.1 Promise is a new solution for asynchronous programming introduced in ES6. Syntactically, a Promise is a constructor that encapsulates an asynchronous operation and can retrieve the result of its success or failure.
- Promise constructor: Promise (excutor) {}
- Promise.prototype.then method chain call
- Promise. Prototype. Catch method
// Instantiate the Promise object
const p = new Promise(function(resolve,reject){
setTimeout(() = >{
let data = 'User data in the database'
// Specify a successful callback
resolve(data)
let err = 'Data read failed'
// Specify a failed callback
reject(err)
},1000)})// Call the then method of the Promise object
p.then(function(value){// A successful callback was executed
console.log(value)
},function(reason){// Failed callback
console.error(reason)
})
Copy the code
13.2 Catch methods for Promise Objects
const p = new Promise((resolve,reject) = >{
setTimeout(() = >{
// Set the state of the p object to failure and set the value of failure
reject('Wrong! ')},1000)})//p.then(function(value){},function(reason){
// console.error(reason)
/ /})
p.catch(function(reason){
console.warn(reason)
})
Copy the code
13.3 The Node environment is required for Promise file reading
//1. Import fs module
const fs = require('fs')
//2. Call the method to read the file
/ / fs. ReadFile ('. / resources for learning. The md ', (err, data) = > {
// If it fails, an error is thrown
//if(err) throw err
// If there are no errors, output the content
//console.log(data.toString())
/ /})
//3. Use the Promise wrapper
const p = new Promise((resolve,reject) = >{
fs.readFile('/ resources for learning. Md'.(err,data) = >{
// If it fails
if(err) reject(err)
// If successful
resolve(data)
})
})
p.then(funstion(value){
console.log(value.toString())
},function(reason){
console.log('Read failed! ')})Copy the code
13.4 Promise if-then methods
// Create a Promise object
const p = new Promise((resolve,reject) = >{
setTimeout(() = >{
resolve('User data')
//reject(' Error! ')
},1000)})The then method returns a Promise object whose state is determined by the result of the callback
// If the result returned in the callback is a non-Promise property with a status of success, the return value is the object's success value
const result = p.then(value= >{
console.log(value)
//1. Non-promise type properties
//return '123'
//2. Is the promise object
return new Promise((resolve,reject) = >{
//resolve('ok')
reject('error')})//3. Throw an error
//throw new Error(' Error! ')
//throw 'error! '
},reason= >{
console.warn(reason)
})
console.log(reasult)
Copy the code
13.5 Promise Practice – Read multiple files
// Import the fs module
const fs = require('fs')
fs.readFile('/ resources for learning. Md'.(err,data1) = >{
fs.readFile('./resources/ md'.(err,data2) = >{
fs.readFile('./resources/ books. Md '.(err,data3) = >{
let result = data1 + '\r\n' + data2 + '\r\n' + data3
console.log(result)
})
})
})
// Use the promise implementation
const p = new Promise((resolve,reject) = >{
fs.readFile('/ resources for learning. Md'.(err,data) = >{
resolve(data)
})
})
p.then(value= >{
return new Promise((resolve,reject) = >{
fs.readFile('./resources/ md'.(err,data) = >{
resolve([value,data]) // pass down
})
})
}).then(value= >{
return new Promise((resolve,reject) = >{
fs.readFile('./resources/ books. Md '.(err,data) = >{
/ / pumped
value.push(data)
resolve(value)
})
})
}).then(value= >{
console.log(value.join('\r\n'))})Copy the code
14. The Set Set
14.1 ES6 provides a new data structure, Set (collection). It is similar to an array, but the values of the members are unique. Collections implement the Iterator interface, so you can use “extension operators” and for… Of traverses, and sets the properties and methods:
- Size returns the number of elements in the collection
- Add adds a new element and returns the current collection
- Delete Deletes the element and returns Boolean
- Has checks whether the collection contains an element, returning Boolean
// Declare a set
let s = new Set(a)let s2 = new Set(['The Big thing'.'Little things'.'Good thing'.'Bad thing'.'Little things'])
// Number of elements
console.log(s2.size)
// Add a new element
s2.add('Happy event')
// Delete elements
s2.delete('Bad thing')
/ / testing
console.log(s2.has('Dregs'))
/ / to empty
s2.clear()
for(let v of s2){
console.log(v)
}
Copy the code
14.2 Set practice
let arr = [1.2.3.4.5.4.3.2.1]
//1. Array decrement
let result = [...new Set(arr)]
/ / 2. The intersection
let arr2 = [4.5.6.5.6]
let result = [...new Set(arr)].filter(item= > new Set(arr2).has(item))
/ / 3. And set
let union = [...new Set([...arr,...arr2])]
console.log(union)
4 / / difference set
let diff = [...new Set(arr)].filter(item= >! (new Set(arr2).has(item)))
Copy the code
15.Map
ES6 provides Map data structures. It is similar to an object, but also a collection of key-value pairs. However, the scope of “keys” is not limited to strings; all types of values (including objects) can be used as keys. Map also implements the Iterator interface, so you can use “extension operators” and for… Of traverses. Map attributes and methods:
- The size returns the number of elements in the Map |
- Set adds a new element that returns the current Map
- Get returns the key value of the keyname object
- Has checks whether the Map contains an element, returning Boolean
- Clear Clears the collection and returns undefined
/ / declare the Map
let m = new Map(a)// Add elements
m.set('name'.'the north')
m.set('change'.function(){
console.log('Change your life')})let key = {
school: 'beida'
}
m.set(key,['Beijing'.'Shanghai'.'shenzhen'])
//size
console.log(m.size)
/ / delete
m.delete('name')
/ / to get
console.log(m.get('change'))
/ / to empty
m.clear()
/ / traverse
for(let v of m){
console.log(v)
}
Copy the code
16. Class class
16.1 ES6 provides a more traditional language approach, introducing the concept of classes as templates for objects. With the class keyword, you can define a class. Basically, ES6 classes can be seen as a syntactic candy that does most of what ES5 does. The new class writing method simply makes object prototype writing clearer and more like object-oriented programming syntax. Knowledge:
- The class declaration class
- Constructor defines the constructor initialization
- Extends extends from the parent class
- Super calls the parent constructor
- Static defines static methods and properties
- Superclass methods can be overridden
//ES5 creates objects through constructors
function Phone(brand,price){
this.brand = brand
this.price = price
}
// Add method
Phone.prototype.call = function(){
console.log('I can make a phone call')}// instantiate the object
let Huawei = new Phone('huawei'.5999)
Huawei.call()
//ES6 class
class Shouji{
// constructor
constructor(brand,price){
this.brand = brand
this.price = price
}
// Methods must use this syntax, not ES5 object holograms
call(){
console.log('I can make a phone call')}}let onePlus = new Shouji('1 +'.1999)
consloe.log(onePlus)
Copy the code
Static member of class 16.2
//function Phone(){
//
/ /}
//Phone. Name = 'Phone'
//Phone.change = function(){
// console.log(' Change the world ')
/ /}
/ / Phone. Prototype. Size = '5.5 inch
//let nokia = new Phone()
//console.log(nokia.name) //undefined
/ / the console. The log (nokia. Size) / / 5.5 inch
class Phone{
// Static attributes
static name = 'mobile phone'
static change(){
console.log('Change the world')}}let nokia = new Phone()
console.log(nokia.name) //undefined
console.log(Phone.name) / / cell phone
Copy the code
16.3 Object Inheritance
//ES5 object inheritance
/ / cell phone
function Phone(brand,price){
this,brand = brand
this.price = price
}
Phone.prototype.call = function(){
console.log('Call')}// Smart phone
function SmartPhone(brand,price,color,size){
Phone.call(this,brand,price) // Call the call method, inheriting the Phone properties
this.color = color
this.size = size
}
// Sets the prototype of the child constructor
SmartPhone.prototype = new Phone
// Declare the method of the subclass
SmartPhone.prototype.photo = function(){
conosle.log('photos')}const chuizi = new SmartPhone('hammer'.2499.'black'.'5.5 inch)
console.log(chuizi)
Copy the code
class Phone(a){
// constructor
constructor(brand,price){
this,brand = brand
this.price = price
}
// Member attributes of the parent class
call(){
console.log('Call')}}// Class inheritance and method rewriting
class SmartPhone extends Phone {
// constructor
constructor(brand,price,color,size){
super(brand,price) //Phone.call(this,brand,price)
this.color = color
this.size = size
}
photo(){
console.log('photos')}// Override the parent class method
call(){
console.log('Video call')}}const xiaomi = new SmartPhone('millet'.799.'black'.'4.7 inch)
console.log(xiaomi)
xiaomi.call() // Video call
xiaomi.photo() / / photo
Copy the code
16.4 get and set
class Phone{
get price() {console.log('Price property read')
return 'iloveyou'
}
set price(newVal) {console.log('The price attribute has been modified')}}// instantiate the object
let s = new Phone()
//console.log(s.price) // Triggers the get method
s.price = 'free' // Trigger the set method
Copy the code
17. Numerical expansion
// 0.number. EPSILON is the minimum precision of JavaScript representation
The value of the EPSILON attribute is close to 2.220446049250313E-16
function equal(a,b){
if(Math.abs(a-b) < Number.EPSILON){
return true
}else{
return false}}console.log(equal(01+0.2.0.3)) //true
//1. Binary and octal decimal and hex
let b = 0b1010
let o = 0o777
let d = 100
let x = oxff
//2.Number.isFinite checks whether a Number isFinite
console.log(Number.isFinite(100)) //true
console.log(Number.isFinite(100/0)) //false
console.log(Number.isFinite(Infinity)) //fasle
//3. number. isNaN checks whether a value isNaN
console.log(Number.isNaN(123))
//4. number. parseInt number. parseFloat The string is converted to an integer
console.log(Number.parseInt('5201314love')) / / 5201314
console.log(Number.parseFloat('3.1415926 magic')) / / 3.1415926
//5. number. isInteger Checks whether a Number is an integer
consoloe.log(Number.isInteger(5)) //true
consoloe.log(Number.isInteger(2.5)) //false
//6.Math.trunc erases the decimal part of a number
consoloe.log(Math.trunc(3.5)) / / 3
Math.sign determines whether a number is positive or negative or zero
console.log(Math.sign(100)) / / 1
console.log(Math.sign(0)) / / 0
console.log(Math.sign(-1000))// -1
Copy the code
18. Object method extension
// 1.object. is Checks whether two values are exactly equal
console.log(Object.is(120.120)) //true
console.log(Object.is(NaN.NaN)) //true
console.log(NaN= = =NaN) //false
//2. Merge object. assign objects
const config1 = {
host: 'localhost'.port: 3306.name: 'root'.pass: 'root'.text: 'test'
}
const config2 = {
host: 'http://baidu.com'.port: 33060.name: 'baidu.com'.pass: 'iloveyou'.text2: 'test2'
}
console.log(Object.assign(config1,config2)) // Config2 overrides the same properties as config1. Different properties are retained
/ / 3. Object. SetPrototypeOf set prototype Object. The Object getPrototypeOf obtain a prototype Object
const school = {
name: 'the north'
}
const cities = {
xiaoqu: ['Beijing'.'Shanghai'.'shenzhen']}Object.setPrototypeOf(school,cities) // This is not recommended
console.log(Object.getPrototypeOf(school))
console.log(school)
Copy the code
19. The modular
19.1 Modularity refers to taking a large program file, splitting it into many smaller files, and then grouping the smaller files together. 19.2 Benefits of Modularity The advantages of modularity include the following:
- Preventing naming conflicts
- Code reuse
- High maintenance
19.3 ES6 Modular syntax
The function of the module consists of two commands: export and import. ● The export command is used to specify external interfaces of a module ● The import command is used to input functions provided by other modules
//m1.js
// Separate exposures
export let school = 'the north'
export function teach(){
console.log('Teach you skills')}Copy the code
//m2.js
// unified exposure
let school = 'the north'
function findJob(){
console.log('Looking for a job')}export {school,findJob}
Copy the code
//m3.js
// Default exposure
export default{
school: 'the north'.change: function(){
console.log('Change you')}}Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>ES6 modular</title>
</head>
<body>
<script type="module">
//1. General import mode
// Import the m1.js module contents
import * as m1 from "./src/js/m1.js"
// Import the m2.js module content
import * as m2 from "./src/js/m2.js"
// Import the m3.js module content
import * as m3 from "./src/js/m3.js"
console.log(m3)
m3.default.change()
//2
import {school, teach} from "./src/js/m1.js"
import {school as beida, findJob} from "./src/js/m2.js"
import {dafault as m3} from "./src/js/m3.js"
//3. Abbreviated form for default exposure (common)
import ms from "./src/js/m3.js"
console.log(m3)
m3.change()
</script>
</body>
</html>
Copy the code
ES7
1. Power calculation of includes and **
// indexOf returns numbers
const mingzhu = [Journey to the West.A Dream of Red Mansions.Romance of The Three Kingdoms.'Water Margin']
/ / determine
console.log(mingzhu.includes(Journey to the West)) //true
console.log(mingzhu.includes('Golden Bottle plum')) //false
/ / * *
console.log(2支那10) / / 1024
console.log(Math.pow(2.10)) / / 1024
Copy the code
ES8
1. The async and await
The combination of async and await syntax makes asynchronous code behave like synchronous code.
2. The async function
1) Async function returns a promise object
2) The result of the Promise object is determined by the return value executed by the async function
/ / async function
async function fn(){
// Returns a string
// return 'Still silicon Valley'
// The return result is not a Promise object, but a success Promise object
// return
// Throws an error and returns a failed Promise
// throw new Error(' Error! ')
// Return a Promise object
return new.Promise((resolve,reject) = >{
// resolve(' successful data ')
reject("Failed mistakes")})}const result = fn()
// Call the then method
result.then(value= > {
console.log(value)
}, reason= > {
console.warn(reason)
})
Copy the code
3. Await expression
1) await must be written in async functions
2) Expression on the right of await – as in promise object
3) await returns the promise success value
4) An await promise fails, and an exception is thrown, which requires a try.. Catch processing
// Create a Promise object
const p = new Promise((resolve,reject) = >{
//resolve(' user data ')
reject('Wrong! ')})// await to be placed in async function
async function main(){
try{
let result = await p
console.log(result)
}catch(e){
console.log(e)
}
}
// Call the function
main()
Copy the code
4. Read files async and await together
//1. Import fs module
const fs = require('fs')
// Reading is learning
function readWeiXue(){
return new Promise((resolve,reject) = >{
fs.readFile(". / resources/learn. Md. "".(err,data) = >{
// If successful
if(! err) resolve(data)// If it fails
reject(err)
})
})
}
function readChaYangShi(){
return new Promise((resolve,reject) = >{
fs.readFile("./resources/ transplanting poems. Md".(err,data) = >{
// If successful
if(! err) resolve(data)// If it fails
reject(err)
})
})
}
function readGuanShu(){
return new Promise((resolve,reject) = >{
fs.readFile("./resources/ md".(err,data) = >{
// If successful
if(! err) resolve(data)// If it fails
reject(err)
})
})
}
Declare an async function
async function main(){
// Get
let weixue = await readWeiXue()
// Get the content of rice transplanting poem
let chayang = await readChaYangShi()
// Get interesting content
let guanshu = await readGuanShu()
console.log(weixue.toString())
console.log(chayang.toString())
console.log(guanshu.toString())
}
main()
Copy the code
5. Combine async and await to encapsulate AJAX requests
// Send an AJAX request that returns a Promise object
function sendAJAX(url){
return new Promise((resolve,reject) = >{
//1. Create objects
const x = new XMLHttpRequest()
/ / 2. The initialization
x.open('GET', url)
/ / 3. Send
x.send()
//4. Event binding
x.onreadystatechange = function(){
if(x.readyState === 4) {if(x.status >=200 && x.status <300) {/ / success
resolve(x.response)
}else{
/ / fail
reject(x.status)
}
}
}
})
}
// promise. then method tests
sendAJAX('https://api.apiopen.top/getJoke').then(value= >{
console.log(value)
},reason= >{})
//async and await tests
async function main(){
let reasult = await sendAJAX('https://api.apiopen.top/getJoke')
// Test again
let tianqi = await sendAJAX('http://www.tianqiapi.com/index/doc?version=day')
console.log(reasult)
}
main()
Copy the code
6.ES8 object method extension
// Declare objects
const school = {
name: 'the north'.cities: ['Beijing'.'Shanghai'.'shenzhen'].xueke: ['front end'.'Java'.'Big Data'.'operations']}// Get all the keys of the object
console.log(Object.keys(school))
// Get all the values of the object
console.log(Object.values(school))
//entries
console.log(Object.entries(school))
/ / create a Map
const m = new Map(Object.entries(school))
console.log(m)
// The object attributes describe the object
conosle.log(Object.getOwnPropertyDescriptors(school))
const obj = Object.create(null, {name: {/ / set the value
value: 'the north'.// Attribute attributes
writable: true.configurable: true.enumerable: true}})Copy the code
ES9
1. Rest parameters and extension operators for objects
The Rest parameter and spread extension operator were introduced in ES6, but only for arrays. Array-like REST parameters and extension operators are provided for objects in ES9
/ / rest parameters
function connect({host, port, ... user}){
console.log(host)
console.log(port)
console.log(user)
}
connect({
host: '127.0.0.1'.port: 3306.username: 'root'.password: 'root'.type: 'master'
})
// Extend operator object merge
const ski1lOne = {
q: 'Sky sound'
}
const skillTwo = {
W: 'Golden bell jar'
}
const skillThree = {
e: 'Thunder in the sky'
}
const skillFour = {
r: 'The Dragon wags its tail'
}
constmangseng = {... skillOne, ... skillTwo, ... skillThree, ... skil1Four}console.log(mangseng)
Copy the code
2. Regular extension – Named capture groups
// Declare a string
let str = '
// Extract the URL and tag text
const reg = /<a = href="(.*)">(.*)<\/a>/
/ / execution
const result = reg.exec(str)
console.log(result[1])
console.log(result[2])
// Named capture groups are easier to maintain than numeric subscripts
const reg = /(?
.*)<\/a>/
const result = reg.exec(str)
console.log(result.groups.url)
console.log(result.groups.text)
Copy the code
3. Regular extension – Reverse assertion
// Declare a string
let str = 'JS5211314 Do you know 555 la la la la '
// Forward assertion
// const reg = /\d+(? =) /
// const result = reg.exec(str)
// Reverse assertion
const reg = / (? < =?) \ d + /
const result = reg.exec(str)
console.log(result)
Copy the code
4. Regular extended-Dotall mode
// dot. metacharacter Any single character other than a newline
let str =` < ul > < li > < a > shoven grams of redemption < / a > < p > release date: 1994-09-10 < / p > < / li > < li > < a > forrest gump < / a > < p > release date: 1994-07-06 < / p > < / li > < / ul > `
// Declare the re
const reg = /\s+(.*?) <\/a>\s+(.*?) <\/p>/
const reg = /.*? (.*?) <\/a>.*? (.*?) <\/p>/g
s
// Perform a match
//const result = reg.exec(str)
let result
let data = []
while(result = reg.exec(str)){
data.push({title: result[1].time: result[2]})}console.log(data)
Copy the code
ES10
1. The Object extension method Object.fromEntries converts a two-dimensional array into an Object
// Two arrays
const result = Object.fromEntries([
['name'.'the north'],
['xueke'.'Java, Big Data, front-end, Cloud Computing ']])//Map
const m = new Map()
m.set('name'.'beida')
const result = Object.fromEntries(m)
Entires ES8 converts an Object into a two-dimensional array
const arr = Object.entires({
name: 'the north'
})
console.log(arr)
Copy the code
2. String extension methods trimStart and trimEnd
//trim Clears the whitespace around the string
let str = ' iloveyou '
console.log(str)
console.log(str.trimStart()) // Clear the left margin of the string
console.log(str.trimEnd()) // Clear the right margin of the string
Copy the code
3. Array extension methods Flat and flatMap
/ / flat
// Convert a multidimensional array to a lower-dimensional array
// const arr = [1,2,3,4,[5,6]]
// const arr = [1,2,3,4,[5,6,[7,8,9]]
// The depth is a number
// console .1og(arr.flat(2))
//flatMap Can be reduced if the return value is a multidimensional array
const arr = [1.2.3.4]
const result = arr.flatMap(item= > [item * 10])
console.log(result);
Copy the code
4.Symbol.prototype.description
/ / create a Symbol
let s = Symbol('the north')
console.log(s.description) / / the north
Copy the code
ES11
1. Private attributes of a class
class Person{
// Public attributes
name;
// Private attributes
#age;
#weight;
// constructor
constructor(name, age, weight){
this.name = name
this.#age = age
this.#weight = weight
}
// Internal access
intro(){
console.log(this.name)
console.log(this.#age)
console.log(this.#weight)
}
}
/ / instantiate
const girl = new Person('little red'.18.'45kg')
console.log(girl.name)
console.log(girl.#age) // Cannot be accessed by instantiating the object
console.log(girl.#weight)
Copy the code
2.Promise.allSettled
// Declare two Promise objects
const p1 = new Promise((resolve, reject) = >{
setTimeout(() = >{
resolve( 'Commodity Data - 1');
}, 1000)})const p2 = new Promise((resolve, reject) = >{
setTimeout(() = >{
resolve('Commodity Data - 2');
// reject(' wrong! ');
}, 1000)})// Calling the allSettled method always returns a successful promise
// const result = Promise.allSettled([p1, p2]);
// the all method returns a successful promise if it succeeds
// const res = Promise.all([p1, p2]);
console.log(res)
Copy the code
3.String.prototype.matchAll
let str =` < ul > < li > < a > shoven grams of redemption < / a > < p > release date: 1994-09-10 < / p > < / li > < li > < a > forrest gump < / a > < p > release date: 1994-07-06 < / p > < / li > < / ul > `
// Declare the re
const reg = /.*? (.*?) <\/a>.*? (.*?) <\/p>/g
s
// Call the method
const result = str.matchAll(reg)
const arr = [...result]
console.log(arr)
Copy the code
4. Optional chain operator
/ /? .
function main(config){
// const dbHost = config && config.db && config.db.host
constdbHost = config? .db? .hostconsole.log(dbHost)
}
main({
db: {host: '192.168.1.100'.username: 'root'
},
cache: {
host: '192.168.1.200'.username: 'admin'}})Copy the code
5. Dynamic import
//hello.js
export function hello(){
alert('Hello')}Copy the code
//app.js
const btn = document.getElementById('btn')
btn.onclick = function(){
// Call the import function to dynamically import modules
import('./hello.js').then(module= >{
module.hello()
})
}
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Dynamic import loading</title>
</head>
<body>
<button id="btn"></button>
<script src="./js/app.js" type="module"></script>
</body>
</html>
Copy the code
6.BigInt
/ / big plastic
//let n = 521n
// console.1og(n, typeof(n))
/ / function
//let n = 123
// console.log(BigInt(n))
// console.log(BigInt(1.2)) // Error
// Large numeric operations
let max = Number.MAX_SAFE INTEGER // The maximum safe integer
console.log(max)
console.1og(max + 1)
console.1og (max + 2) // The operation is abnormal
console.log(BigInt(max))
console.1og(BigInt(max) + BigInt(1))
console.log(BigInt(max) + BigInt(2))
Copy the code
7. The absolute global object globalThis
Always point to window no matter what the environment is, okay