• 使用 class,避免直接操作 prototype

      // 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
        }
      }
    • 使用 extends 来实现继承

      原因:这是一个不会破坏 instanceof 的内建实现原型式继承的方式

      // bad
      const inherits = require('inherits')
      function PeekableQueue(contents) {
        Queue.apply(this, contents)
      }
      inherits(PeekableQueue, Queue)
      PeekableQueue.prototype.peek = function () {
        return this.queue[0]
      }
      
      // good
      class PeekableQueue extends Queue {
        peek () {
          return this.queue[0]
        }
      }
    • 如果未声明构造函数,则类会有一个默认的构造函数,没必要用空的构造函数或者将其委托给父类,eslint: no-useless-constructor

      // bad
      class Jedi {
        constructor () {}
      
        getName() {
          return this.name
        }
      }
      
      // bad
      class Rey extends Jedi {
        constructor (...args) {
          super(...args)
        }
      }
      
      // good
      class Rey extends Jedi {
        constructor (...args) {
          super(...args)
          this.name = 'Rey'
        }
      }
    • 避免类成员重复,eslint: no-dupe-class-members

      原因:重复的类成员声明会默认使用最后声明的,通常会导致 bug

      // bad
      class Foo {
        bar () { return 1 }
        bar () { return 2 }
      }
      
      // good
      class Foo {
        bar () { return 1 }
      }
      
      // good
      class Foo {
        bar () { return 2 }
      }
    文档更新时间: 2021-05-11 16:00   作者:姚连洲