没有规矩 不成方圆es6
用let
替换var来定义变量. 若是是常量,使用const
数组
静态字符串
统一用单引号''
, 动态拼接成的字符串
统一用反引号
``app
let staticString = 'This is a static string'; let d = 'dynamic'; let dynamicString = `This is a ${d} string`;
使用数组成员对变量赋值时,尽可能用解构赋值ui
let arr = [1,2,3,4]; let [arr1,arr2] = arr; //arr1 =1, arr2 = 2;
往对象里添加/修改属性时,使用Object.assign
,而不用松散的.语法
es5
const objectA = {}; Object.assign(objectA, { attr1: 3 }); //objectA{attr1:3}
面向对象的写法一概写成class
的形式,摒弃原生的prototype的书写方法prototype
class A{ constructor(){} prototypeFunA(){} static staticFunA(){} ... }
用extends实现单继承, 摒弃原生的prototype链书写方法的继承code
class A{ constructor(){} prototypeFunA(){} static staticFunA(){} ... } class B extends A{ constructor(){ super(); } } let b = new B(); b.prototypeFunA(); B.staticFunA();
用mixin修饰器的方式能够多继承(es5中能够用call来实现多继承,不过call/apply方法都属于奇技淫巧,不推荐使用了)
,实际上在js中多继承的应用场景并很少见对象
模块的书写, 相似CommonJs规范. 暴露方法/属性统一用export继承
//moduleA.js export let name = 'Xie Min'; export function fun1(){xxx} export function fun1(){xxx} //或者这样写 //moduleA.js let name = 'Xie Min'; function fun1(){xxx} function fun1(){xxx} export{ name, fun1, fun2, }
引用模块统一用import,摒弃掉require
. 这里特别注意,import模块的时候路径必须写成相对路径的形式, 好比要写成 import {xx} from './moduleA'
而不是 import {xx} from 'moduleA'
ip
//index.js import * as moduleA from './moduleA'; moduleA.name; moduleA.fun1(); moduleA.fun2();
部分参考自 阮一峰《ECMAScript 6入门》 其余细节待补充