转至阮一峰的ECMAScript6入门 http://es6.ruanyifeng.com/#docs/style
es6知识点
编程风格
let
代替var
- 全局常量和线程安全
- 在
let
和const
之间优先使用const
,尤其是在全局环境下 - 所有函数声明都应该设置为常量
const
,符合函数式编程思想 const
声明,阅读代码的人立刻会意识到不应该修改这个值const
防止无意间修改变量所导致的错误- 多使用
const
有利于提高程序运行效率,let
和const
的本质区别就是编译器内部的处理不同
- 静态字符串一律使用单引号
'this is a static string'
- 动态字符串一律使用反引号
this is a ${data} active string
- 使用数组成员对变量赋值时,优先使用解构赋值
const arr = [1,2,3];
const [first, second] = arr;
- 如果函数参数为对象时,优先使用对象的解构赋值
function getFullName(user) {
const { firstName, lastName } = user;
}
- 如果函数返回多个值,优先使用对象的解构赋值
function fn() {
return { left, right, top, bottom }
}
const { left, right } = fn()
- 单行定义对象,最后一个成员不以逗号结尾;多行定义对象,最后一个成员以逗号结尾
const a = { k1: v1, k2: v2 };
const b = {
k1: v1,
k2: v2,
};
- 对象尽量静态化,使用
const
声明,一旦定义,就不得随意添加新的属性。如果添加属性不可避免,要使用Object.assign
方法
const a = { k1: v1, k2: v2 };
Object.assign(a, { k3: v3 });
- 对象的声明尽量采用简洁的表达方式
const name = 'Jack';
const obj = {
name,
age: 18,
sayName() {
return this.age;
},
}
- 立即执行函数可以写成箭头函数
(() => {
console.log('this is a IIFE function');
})();
- 需要使用函数表达式的场合尽量使用箭头函数代替
arr.sort((a, b)=>{
return a-b;
});
const newarr = arr.map(x => x**2);
- 给函数参数设置默认值
function fn(opts = {}) {
}
- 注意区分
Object
和Map
,只有模拟现实世界的实体对象时采用Object
。如果只是需要key: value
结构,使用Map
结构 - 用
Class
代替prototype
操作;使用extends
实现继承
class Queue {
constructor(content = []) {
this._queue = [...content];
}
pop() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
}
class PeekableQueue extends Queue {
peek() {
return this._queue[0];
}
}
- 使用
import``export
的模块写法
import { func1, func2 } from 'moduleA';
export default ModuleB;