技术实践
常用的ECMAScript6语法有哪些?
ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体

let, const, class, import, export, export default, Promise, async, await, for await, Object.values,Object.kes, array.form array.reduce
for...of 和 for...in
for...of 用于遍历一个迭代器,如数组:
js
let letter = ['a', 'b', 'c'];
letter.size = 3;
for (let letter of letters) {
console.log(letter);
}
// 结果: a, b, c
for...in 用来遍历对象中的属性:
js
let stu = ['Sam', '22', '男'];
stu.size = 3;
for (let stu in stus) {
console.log(stu);
}
// 结果: Sam, 22, 男
对象超类
ES6 允许在对象中使用 super 方法:
js
ar parent = {
foo() {
console.log("Hello from the Parent");
}
}
var child = {
foo() {
super.foo();
console.log("Hello from the Child");
}
}
Object.setPrototypeOf(child, parent);
child.foo(); // Hello from the Parent
// Hello from the Child
函数的参数默认值
js
// ES6之前,当未传入参数时,text = 'default';
function printText(text) {
text = text || 'default';
console.log(text);
}
// ES6;
function printText(text = 'default') {
console.log(text);
}
printText('hello'); // hello
printText();// default
箭头函数(Arrow Functions)
ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体;
箭头函数最直观的三个特点:
- 不需要 function 关键字来创建函数
- 省略 return 关键字
- 继承当前上下文的 this 关键字
js
// ES5
var add = function (a, b) {
return a + b;
};
// 使用箭头函数
var add = (a, b) => a + b;
// ES5
[1,2,3].map((function(x){
return x + 1;
}).bind(this));
// 使用箭头函数
[1,2,3].map(x => x + 1);