There are four categories of new features:
1. Solve some problems or deficiencies in the original grammar
2. Enhance the original grammar
3. Brand new objects, brand new methods, brand new functions
4. Brand new data types and data structures
1. Let, Const and block-level scope
Before ES2015, there were only global scope and function scope. Now it is possible to declare Let and Const as defined variables in the block-level scope, and will not be declared in advance.
for (let i = 0; i < 3; i++) {
let i = 'foo'
console.log(i)
}
2. Deconstruction of arrays and objects
We can deconstruct arrays and objects like this:
const [foo, bar, baz] = arr
const { name } = obj
Three, template string
The template string (`) supports line breaks and inserts some parameters through the expression ${}.
function myTagFunc (strings, name, gender) {
// console.log(strings, name, gender)
const sex = gender ? 'man' : 'woman'
return strings[0] + name + strings[1] + sex + strings[2]
}
const result = myTagFunc`hey, ${name} is a ${gender}.`
We can also define a label for him like this, and he will run this method to replace the content
Fourth, some extension methods of string
const message = 'Error: foo is not defined.'
console.log(
message.startsWith('Error')
message.endsWith('.')
message.includes('foo')
)
Five, function parameter default value
We can pass function(value = true){} to pass in a default value, and parameters with default values should be placed as far back as possible.
Six, remaining parameters
We can pass function(value,...args){} to pass in a remaining parameter, this parameter can only be used once, and only in the last one.
Seven, expand the array
const arr = [1,2,3]; consoel.log (... arr); // 1 2 3
Eight, arrow function
Ordinary function function ()() Arrow function () => (); v => v + 1;
When there is only one sentence, {} can be omitted, and when {} is not added, this sentence will be returned as the result.
In addition, the arrow function has no this statement, and it will continue to use the outer this point.
Nine, the enhancement of object literals in ES2015
const bar = '345'
const obj = {
foo: 123,
// bar: bar
// 属性名与变量名相同,可以省略 : bar
bar,
// method1: function () {
// console.log('method111')
// }
// 方法可以省略 : function
method1 () {
console.log('method111')
// 这种方法就是普通的函数,同样影响 this 指向。
console.log(this)
},
// Math.random(): 123 // 不允许
// 通过 [] 让表达式的结果作为属性名
[Math.random()]: 123
}
Ten, Object extension methods assgin and is
const obj = { name: 'global obj' };
const funObj = Object.assign({},obj);
console.log(
0 == false // => true
0 === false // => false
+0 === -0 // => true
NaN === NaN // => false
Object.is(+0, -0) // => false
Object.is(NaN, NaN) // => true
)
11. Proxy object
const person = {
name: 'zce',
age: 20
}
const personProxy = new Proxy(person, {
get (target, property) {
console.log('get', property)
return target[property]
},
set (target, property, value) {
console.log('set', property, value)
target[property] = value
}
})
personProxy.name = 'jack'
console.log(personProxy.name)
Used to monitor object property modification and read behavior
Twelve, static class Reflect
Reflect has a total of thirteen methods, sorting out some relatively scattered object operations, used to replace some of the previous methods, here are three more commonly used examples.
const obj = {
name: 'zce',
age: 18
}
// console.log('name' in obj)
// console.log(delete obj['age'])
// console.log(Object.keys(obj))
console.log(Reflect.has(obj, 'name'))
console.log(Reflect.deleteProperty(obj, 'age'))
console.log(Reflect.ownKeys(obj))
13. Promise
Used for more concise and convenient asynchronous methods that can be called in chain.
14. Class defines a class
class Person {
//构造函数
constructor (name) {
this.name = name
}
static of (name){
return new Person(name)
}
say () {
console.log(`hi, my name is ${this.name}`)
}
}
15. Class inheritance
class MyPromise extends Promise{
//super代表父类
super.resolve()
}
16. Set data structure
Commonly used to remove duplicates in the interview question array const result = [...new Set([1,1,1,1,2,3,4])] // [1,2,3,4]
const s = new Set()
s.add(1).add(2).add(3).add(4).add(2)
s.forEach(i => console.log(i))
console.log(s.size)
console.log(s.has(100))
console.log(s.delete(3))
s.clear()
17. Map data structure
Map is a collection of key-value pairs in the true sense. It can use any type of value as a key, while objects can only use strings as keys.
const m = new Map()
const tom = { name: 'tom' }
m.set(tom, 90)
console.log(m)
console.log(m.get(tom))
// m.has()
// m.delete()
// m.clear()
m.forEach((value, key) => {
console.log(value, key)
})
Seventeen, generator function Generator
Use function * foo(){}, yield as a breakpoint instead of return, and then use foo.next() to continue execution.
The following is an asynchronous solution with Promise:
function ajax (url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.send()
})
}
function * main () {
try {
const users = yield ajax('/api/users.json')
console.log(users)
const posts = yield ajax('/api/posts.json')
console.log(posts)
const urls = yield ajax('/api/urls.json')
console.log(urls)
} catch (e) {
console.log(e)
}
}
function co (generator) {
const g = generator()
function handleResult (result) {
if (result.done) return // 生成器函数结束
result.value.then(data => {
handleResult(g.next(data))
}, error => {
g.throw(error)
})
}
handleResult(g.next())
}
co(main)
18. Symbol data type
The seventh data type after String, Number, Null, Undefined, Boolean, and Object
It can prevent extended objects and property name conflicts. Two Symbols will never be equal. You can use Symbols to add unique keys to objects to realize private members of objects.
const name = Symbol()
const person = {
[name]: 'zce',
say () {
console.log(this[name])
}
}
Nineteen, iterator iterator
Declaring an iterator in an object can throw a traversal interface to the outside. This is the principle of for...of, we can declare this iterator in any object, and then give a method we want to expose a loop method. A generator function Generator is mounted internally, and externally, it is implemented using a loop + next() method.
const todos = {
life: ['吃饭', '睡觉', '打豆豆'],
learn: ['语文', '数学', '外语'],
work: ['喝茶'],
[Symbol.iterator]: function * () {
const all = [...this.life, ...this.learn, ...this.work]
for (const item of all) {
yield item
}
}
}
for (const item of todos) {
console.log(item)
}