kam*_*o94 7 javascript inheritance ecmascript-6
假设我有两节课,A并且B. B扩展A并因此继承其所有方法。如果我愿意的话,我也可以覆盖它们。我的问题是我是否可以阻止B继承A. 到目前为止我所尝试的看起来像这样。
// setup
class A {
constructor(x) {
this.x = x;
}
valueOf() {
return this.x;
}
toString() {
return `{x:${this.x}}`;
}
}
class B extends A {
constructor(x) {
super(x);
delete this.valueOf;
}
}
delete B.prototype.valueOf;
// example
const a = new A(42);
const b = new B(42);
// should work
console.log(a.valueOf());
// should throw TypeError, not a function
console.log(b.valueOf());Run Code Online (Sandbox Code Playgroud)
实际上valueOf这是一个坏例子,因为每个对象都从Object.prototype. 尝试console.log(({}).valueOf())
但你可以通过隐藏这个属性来解决这个问题
// setup
class A {
constructor(x) {
this.x = x;
}
valueOf() {
return this.x;
}
toString() {
return `{x:${this.x}}`;
}
}
class B extends A {
get valueOf() { return undefined }
}
class C extends A {
}
Object.defineProperty(C.prototype, 'valueOf', {})
// example
const a = new A(42);
const b = new B(42);
const c = new C(42);
// should work
console.log(a.valueOf());
// should throw TypeError, not a function
try {
console.log(b.valueOf());
} catch (e) {
console.log(e.message)
}
try {
console.log(c.valueOf());
} catch (e) {
console.log(e.message)
}Run Code Online (Sandbox Code Playgroud)