ES6学习16章:编程风格

编程风格

如何将ES6新语法,运用到编码实践之中,与传统的JavaScript语法结合在一起,写出合理的,易于阅读和维护的代码?

块级作用域

1. let取代var

ES6的声明变量的命令:let和const,其中let可以完全取代var,无副作用

'use strict'
if(true){
    let x = 'hello'
}
for(let i=0;i<10;i++){console.log(i)}
  • 使用let不会增加过多的全局变量,因为let有块级作用域。
  • 使用let不存在变量提升,因此要遵循先声明后使用的原则。

2. 全局常量和线程安全

在全局环境中,建议优先使用const设置常量 而不是let设置变量。有利于将来的分布式运算。const声明有两个好处:1. 阅读代码的人立刻会意识到不应该修改这个值,2.防止了无意间修改变量值所导致的错误

// bad
var a=1,b=2,c=3;
// good
const a=1;
const b=2;
const c=3;
// best
const [a,b,c]=[1,2,3]

字符串

  1. 静态字符串一律使用单绰号或反绰号,不使用双绰号。动态字符串使用反引号
// bad
const a = "footbar"
const b = 'foo' + a+'bar'
// acceptable
const c=`foobar`
// good
const a = 'foobar'
const b = `foo${a}bar`

解构赋值

  1. 使用数组成员对变量赋值时,优先使用解构赋值
const arr = [1,2,3,4]
// good
const [first,second]=arr
// bad
const first = arr[0];
const seconde = arr[1];
  1. 函数的参数如果是对象的成员,优先使用解构赋值
// bad
function getFullName(user){
    const firstName = user.firstName;
    const secondName = user.secondName;
}
// good
function getFullName(user){
    const {firstName,secondName}=user
}
// best
function getFullName({firstName,secondName}){}
  1. 函数返回多个值,优先使用对象的解构赋值,而不是数组的解构赋值。这样全球以后添加返回值,以及更改返回值的顺序。
function process(input){
    return {left,right,top,bottom}
}
const {left, right}=process(input)

对象

  1. 单行定义的对象,最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾。
// bad
const a = {k1:v1,k2:v2,} //单行逗号不结尾
const b = {
    k1:v1,
    k2:v2   // 多行逗号结尾
}
// good
const a = {k1:v1,k2:v2}
const b ={
    k1:v1,
    k2:v2,
}
  1. 对象尽量静态化,一旦定义,就不得随意添加新的属性。如果添加属性不可避免,要使用Object.assign方法。
// bad 
consts a= {}
a.x=3
// good
const a = {x:null}
a.x =3
// 如果无可避免
const a= {}
Object.assign(a,{x:3})
  1. 如果对象的属性名是动态的,可以在创建对象的时候,使用属性表达式定义
const obj={
    id:4,
    name:'hello',
    [getKey('enabled')]:true
}
// 最后一个属性需要通过计算得到,此时最好采用属性表达式,在新建obj的时候,将该属性与其他属性定义在一起
  1. 对象的属性和方法,尽量采用简洁表达法,这样易于描述和书写
var ref = 'some value'
// bad
const atom={
    ref:ref,
    value:1,
    addValue:function(value){
        return atom.value + value;
    }
}
// good
const atom= {
    ref,
    value:1,
    addValue(){
        return atom.value + value
    }
}

数组

  1. 使用扩展运算符(…)拷贝数组
const itemCopy = [...items]
  1. 使用Array.from方法,将类似数组的对象转为数组
const foo = document.querySelectorAll('.foo')
const nodes = Array.from(foo)

函数

  1. 立即执行函数可以写成箭头函数的形式
(()=>{
    console.log('hello U')
})()
  1. 那些需要使用函数表达式的场合,尽量用箭头函数代替。因为这样更简洁,而且绑定了this
// bad
[1,2,3].map(function(x){
    return x*x
})
// good
[1,2,3].map(x=>{
    return x*x
})
// best
[1,2,3].map(x=>x*x)
  1. 箭头函数取代Function.prototype.bind,不应该再用self/_this/that绑定this
// bad
const self = this;
const boundMethod = function(...params){
    return method.apply(self,params)
}
// acceptable
const boundMethod = method.bind(this)
// best 
const boundMethod = (...params)=>method.apply(this,params)
  1. 简单,单行的,不会利用的函数,建议有采用箭头函数。如果函数体较为复杂,行数较多,应该采用传统的函数写法。
  2. 使用默认值语法来设置函数参数的默认值
// good
function method(opts = {}){
    //...
}
// bad
function method(opts){
    opts = opts||{}
}
  1. 使用res运行符,而不是arguments来获取参数
// bad
function method(){
    const args = Array.prototype.slice.call(arguments)
    return args.join('')
}
// good
function method(...args){
    return args.join('')
}

Map结构

注意区分Object和Map,只有模拟现实世界的实体对象时,才使用Object。如果只是需要key:value的数据结构,使用Map结构。因为Map有内建的遍历机制

let map = new Map(arr)
for(let key of map.keys()){
    console.log(key)
}
for(let value of map.values()){
    console.log(value)
}
for(let item of map.entries()){
    console.log(item[0],item[1])
}

Class

  1. 总是用Class,取代需要prototype的操作。因为Class的写法更简洁,更易于理解。
// bad 
function Queue(contents = []){
    this._queue = [...contents]
}
Queue.prototype.pop = function(){
    const value = this._queue[0]
    this._queue.splice(0,1)
    return value
}
// good
class Queue{
    constructor(contents = []){
        this._queue = [...contents]
    }
    pop(){
        const value = this._queue[0]
    this._queue.splice(0,1)
    return value
    }
}
  1. 使用extends实现继承,这样更简单,不会破坏instanceof运算的危险
// bad 
const inherites = require('inherits')
function Queue(contents){
    Parent.apply(this,contents)
}
inherits(Queue,Parent)
Queue.prototype.peek = function(){
    return this._queue[0]
}
// good
class Queue extends Parent{
    peek(){
        return this._queue[0]
    }
}

模块

  1. Module语法是JS模块的标准语法,坚持使用这种写法,用import 取代require
// bad
const moduleA = require('moduleA')
const fun = moduleA.fun
// good 
import {fun} from './moduleA'
  1. 使用export 取代module.exports
// commonjs写法
var react = require('react')
var Breadcrumbs = React.createClass({
    render(){
        return <nav />
    }
})
module.exports = Breadcrumbs

// ES6写法
import React from 'react'
const BreadCrumbs = React.createClass({
    render(){
        return <nav />
    }
})
export default BreadCrumbs
  1. 如果模块只输出一个值,就使用export deafult.如果要输出多个值,就用export且不使用export default.(不要export default与export同时使用)
  2. 模块输入时,不要使用通配符。这样可以确保模块之中,有一个默认出出(export default)
// bad 
import * as myObject './importModule'
// good
import myObject from './importModule'
  1. 模块输出一个函数时,首字母应该小写
function method(){}
export default method
  1. 模块输出对象时,对象名首字母大写
const StyleGuide={
    es6:{}
}
export default StyleGuide

ESLint的使用

ESLint是一个语法规则和代码风格的检查工具,可以用来保证写出语法正确、风格统一的代码。

# 安装
npm i -g eslint
# 安装Airbnb语法规则
npm i -g eslint-config-airbnb
# 根目录创建配置文件 .eslintrc
{
    "extends":"eslint-config-airbnb"
}
# 使用eslint检查代码 (cmd中)
eslint index.js
发布了114 篇原创文章 · 获赞 146 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/Sophie_U/article/details/79021335
今日推荐