4

假设我们有:

class FinalClass {
  ...
}

如何修改它以使

class WrongClass extends FinalClass {
  ...
}

或者

new WrongClass(...)

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

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

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

4

2 回答 2

13

检查this.constructor构造函数,FinalClass如果它不是自身,则抛出。(借用检查this.constructor而不是this.constructor.name来自@Patrick Roberts。)

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

于 2016-08-03T16:03:29.663 回答
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
}())

于 2016-08-03T16:21:48.517 回答