寫一手漂亮的js

介紹

看了不少best practice,卻沒有人教我怎麼去寫一手漂亮的js代碼,今天我來說講我本身寫js的經驗javascript

不要在代碼中留大段註釋掉的代碼

  • 留給git去管理,否則你要git幹嗎
// bad

// function add() {
//   const a = b + c
//   return a
// }

function add() {
  return a + 1000
}

// good
function add() {
  return a + 1000
}

適當地換行

// bad
function a() {
  const {
    state_a,
    state_b,
    state_c
  } = this.state
  this.setState({state_a: state_a * 2})
  return 'done'
}

// good
function a() {
  const {
    state_a,
    state_b,
    state_c
  } = this.state

  this.setState({state_a: state_a * 2})

  return 'done'
}

適當的添加註釋,但不要瘋狂的添加註釋

  • 對一段代碼或者一行特別須要注意的代碼註釋
  • 不要瘋狂的註釋,太囉嗦,漂亮的代碼本身會說話
// bad
const a = 'a' // 這是a
const b = 'b' // 這是b
const c = 'c' // 這是c

// good
/**
 * 申明變量
 */
 const a = 'a'
 const b = 'b'
 const c = 'c'

將相似行爲、命名的代碼歸類在一塊兒

// bad
function handleClick(arr) {
  const a = 1

  arr.map(e => e + a)

  const b = 2

  return arr.length + b
}

// good
function handleClick(arr) {
  const a = 1
  const b = 2

  arr.map(e => e + a)

  return arr.length + b
}

在不破壞語義性的狀況下,'能省則省'

  • 牢記js中函數是一等公民
  • 可是,若是省略到影響可讀性了,就是失敗的
  • 在可讀性和簡潔性至今必須選一個的話,永遠先選可讀性
function add(a) {
  return a + 1
}

function doSomething() {

}

// bad
arr.map(a => {
  return add(a)
})

setTimeout(() => {
  doSomething()
}, 1000)

// good
arr.map(add)

setTimeout(doSomething, 1000)
  • 箭頭函數
// bad
const a = (v) => {
  return v + 1
}

// good
const a = v => v + 1


// bad
const b = (v, i) => {
  return {
    v,
    i
  }
}

// good
const b = (v, i) => ({v, i})


// bad
const c = () => {
  return (dispatch) => {
    // doSomething
  }
}

// good
const c = () => dispatch => {
  // doSomething
}
  • 提早對對象取值(寫react的同窗必定懂)
// bad
const a = this.props.prop_a + this.props.prop_b

this.props.fun()

// good
const {
  prop_a,
  prop_b,
  fun
} = this.props

const a = prop_a + prop_b

fun()

合理使用各類表達式

// bad
if (cb) {
  cb()
}

// good
cb && cb()


// bad
if (a) {
  return b
} else {
  return c
}

// good
return a ? b : c


// bad
if (a) {
  c = a
} else {
  c = 'default'
}

// good
c = a || 'default'

鏈式調用寫法

// bad
fetch(url).then(res => {
  return res.json()
}).then(() => {
  // doSomething
}).catch(e => {

})

// good
fetch(url)
  .then(res => {
    return res.json()
  })
  .then(() => {
    // doSomething
  })
  .catch(e => {

  })

保持代碼是縱向發展的

  • 發現那些在整個文件中特別'突出'的代碼時,應該考慮對他們作換行處理了
// bad
return handleClick(type, key, ref, self, source, props)

// good
return handleClick(
  type,
  key,
  ref,
  self,
  source,
  props
)

// bad
const a = this.props.prop_a === 'hello' ? <di>world</div> : null

// good
const a = this.props.prop_a === 'hello'
  ? <di>world</div>
  : null

總結

我的經驗,若有錯誤,還望指正java

相關文章
相關標籤/搜索