当前位置: 首页 > Web前端 > HTML

ChetuCub的自我修养-[ES6]编程风格规范

时间:2023-04-02 11:08:29 HTML

前言无规矩,不成规矩。使用let代替var来定义变量。如果是常量,使用const静态字符串加单引号'',动态拼接的字符串加反引号``letstaticString='Thisisastaticstring';letd='dynamic';letdynamicString=`Thisis一个${d}字符串;在使用数组成员给变量赋值时,尽量使用解构赋值letarr=[1,2,3,4];let[arr1,arr2]=arr;//arr1=1,arr2=2;给对象添加/修改属性时,使用Object.assign代替松散的语法constobjectA={};Object.assign(objectA,{attr1:3});//objectA{attr1:3}面向对象的写法一直写成class的形式,放弃原来的原型写法classA{constructor(){}prototypeFunA(){}staticstaticFunA(){}...}使用extends实现单继承,放弃原来的原型链写方法继承classA{constructor(){}prototypeFunA(){}staticstaticFunA(){}...}classBextendsA{constructor(){super();}}让b=新B();b.prototypeFunA();B.staticFunA();使用mixin修饰符可以实现多重继承(在es5中可以使用call实现多重继承,但是call/apply方法是trick,不推荐),其实在js中多重继承的应用场景并不多。模块的写法类似于CommonJs规范。使用export//moduleA.jsexportlet统一暴露方法/属性name='XieMin';exportfunctionfun1(){xxx}exportfunctionfun1(){xxx}//或者这样写//moduleA.jsletname='谢敏';functionfun1(){xxx}functionfun1(){xxx}export{name,fun1,fun2,}引用模块统一导入,require丢弃。这里要特别注意,importmodule的路径一定要写成相对路径的形式,比如import{xx}from'./moduleA'而不是import{xx}from'moduleA'//index.jsimport*作为来自'./moduleA'的moduleA;moduleA。姓名;moduleA.fun1();moduleA.fun2();结论部分参考阮一峰《ECMAScript 6入门》其他细节待补充