假设我们有:
class FinalClass {
...
}
如何修改它以制作
class WrongClass extends FinalClass {
...
}
或
new WrongClass(...)
生成异常?也许最明显的解决方案是在FinalClass的构造函数中执行以下操作:
if (this.constructor !== FinalClass) {
throw new Error('Subclassing is not allowed');
}
有没有人有更清洁的解决方案,而不是在每个应该是最终的类中重复这些行(可能是装饰器)?
答案 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
}())