ES6/7 新特性
- 字符串模版
- let
- const
- 箭头函数(默认参数)
const action = (num = 10)=> console.log(num)
action()
action(300)
- 对象初始化简写
var name = "dukai"
var age = 28
var person = {name, age}
- 对象方法简写
- Object.assign()这个方法来实现浅复制
- 解构
//对象
const people = {
name: 'dukai',
age: 28
}
const { name, age } = people
console.log(`${name}: ${age}`)
//数组
const color = ['red', 'blue']
const [first, second] = color
console.log(first, second)
- Spread Operator 展开运算符
// 数组
const color = ['red', 'yellow']
const colorful = [...color, 'green', 'pink']
console.log(colorful) //[red, yellow, green, pink]
// 对象
const child = { fist: 'a', second: 'b'}
const parent = { ...child, third: 'c' }
console.log(parent)
// 获取其中的一部分
// 数组
const number = [1,2,3,4,5]
const [one, ...part] = number
console.log(one) //1
console.log(part) //2,3,4,5
// 对象
const user = {
username: 'dk',
gender: 'male',
age: 28,
address: 'Beijing'
}
const { username, ...part } = user
console.log(part) //{ "gender": "male, "age": 19,"address": "Beijing"}
// 合成新对象,当重名时,**后覆盖前**
const first = {
a: 1,
b: 2,
c: 6,
}
const second = {
c: 3,
d: 4
}
const total = { ...first, ...second }
console.log(total) // { a: 1, b: 2, c: 3, d: 4 }
- import导入模块、export导出模块
1. 当用export default people导出时,就用 import people 导入(不带大括号)
2. 一个文件里,有且只能有一个export default。但可以有多个export。
3. 当用export name 时,就用import { name }导入(记得带上大括号)
4. 当一个文件里,既有一个export default people, 又有多个export name 或者 export age时,导入就用 import people, { name, age }
5. 当一个文件里出现n多个 export 导出很多模块,导入时除了一个一个导入,也可以用import * as example
- Promise
setTimeout(function() {
console.log(1)
}, 0);
new Promise(function executor(resolve) {
console.log(2);
for( var i=0 ; i<10000 ; i++ ) {
i == 9999 && resolve();
}
console.log(3);
}).then(function() {
console.log(4);
});
console.log(5);
Generators – 生成器, 是能返回一个迭代器的函数
有点难度的来了 async 返回一个 Promise 对象(比 Generators 语义性更好)
async function reqApis(name) {
var user = await req.getUser(name);
var articles = await req.getArticles(user.id);
// it is real article list here, but if returned it'll be a Promise
return articles;
}
// Becuase of the 'async' the result is Promise,
// so we should use it like this
reqApis('dukai').then((articles)=> {
renderArticles(articles)
})
- Class 关于类的使用
class Person {
constructor(type) {
this.type = type;
}
says(say) {
console.log(`${this.type} says ${say}`);
}
}
let person = new Person("person");
person.says('hello');
class Man extends Person {
constructor(type, age) {
super(type);
this.type = type;
this.age = age
}
says(say) {
console.log(`${this.type} says ${say}, I'm ${this.age} years old.`);
}
}
let jack = new Man("dukai", 28);
jack.says('hello');
对象深拷贝的奇技淫巧 非 ES6/7专属,但属性中有方法或者循环引用,你就老实用循环递归吧
var new_arr = JSON.parse( JSON.stringify(arr) );