如何使ES6类成为最终(非子类)

时间:2016-08-03 15:50:52

标签: javascript ecmascript-6 ecmascript-next

假设我们有:

class FinalClass {
  ...
}

如何修改它以制作

class WrongClass extends FinalClass {
  ...
}

new WrongClass(...)

生成异常?也许最明显的解决方案是在FinalClass的构造函数中执行以下操作:

if (this.constructor !== FinalClass) {
    throw new Error('Subclassing is not allowed');
}

有没有人有更清洁的解决方案,而不是在每个应该是最终的类中重复这些行(可能是装饰器)?

2 个答案:

答案 0 :(得分:7)

this.constructor的构造函数中检查FinalClass,如果它本身不是则抛出。 (从@Patrick Roberts借用this.constructor代替this.constructor.name

class FinalClass {
  constructor () {
    if (this.constructor !== FinalClass) {
      throw new Error('Subclassing is not allowed')
    }
    console.log('Hooray!')
  }
}

class WrongClass extends FinalClass {}

new FinalClass() //=> Hooray!

new WrongClass() //=> Uncaught Error: Subclassing is not allowed

或者,如果有支持,请使用new.target。谢谢@loganfsmyth。

class FinalClass {
  constructor () {
    if (new.target !== FinalClass) {
      throw new Error('Subclassing is not allowed')
    }
    console.log('Hooray!')
  }
}

class WrongClass extends FinalClass {}

new FinalClass() //=> Hooray!

new WrongClass() //=> Uncaught Error: Subclassing is not allowed

______

正如您所说,您也可以使用装饰器来实现此行为。

function final () {
  return (target) => class {
    constructor () {
      if (this.constructor !== target) {
        throw new Error('Subclassing is not allowed')
      }
    }
  }
}

const Final = final(class A {})()

class B extends Final {}

new B() //=> Uncaught Error: Subclassing is not allowed
    

正如Patrick Roberts在评论中所说,装饰器语法@final仍在提案中。可以使用Babel和babel-plugin-transform-decorators-legacy

答案 1 :(得分:3)

constructor.name很容易欺骗。只需使子类与超类同名:



class FinalClass {
  constructor () {
    if (this.constructor.name !== 'FinalClass') {
      throw new Error('Subclassing is not allowed')
    }
    console.log('Hooray!')
  }
}

const OopsClass = FinalClass

;(function () {
  class FinalClass extends OopsClass {}

  const WrongClass = FinalClass

  new OopsClass //=> Hooray!

  new WrongClass //=> Hooray!
}())




最好检查constructor本身:



class FinalClass {
  constructor () {
    if (this.constructor !== FinalClass) {
      throw new Error('Subclassing is not allowed')
    }
    console.log('Hooray!')
  }
}

const OopsClass = FinalClass

;(function () {
  class FinalClass extends OopsClass {}

  const WrongClass = FinalClass

  new OopsClass //=> Hooray!

  new WrongClass //=> Uncaught Error: Subclassing is not allowed
}())