比方说,我有一个超类和一个重写超方法之一的孩子。
class Test {
doSomething() {
callsomething({
callback: this.method
})
}
method() {
console.log('parent');
}
}
class A extends Test {
constructor() {
super();
}
method() {
console.log('override');
}
}
new A().method();
有一种方法可以在Test
类中知道method
是否被覆盖?
答案 0 :(得分:3)
在doSomething
内,检查this.method
是否引用了Test.prototype.method
-如果不是,则this.method
引用了其他内容,这意味着它已经被遮盖了,很可能通过子类方法:
class Test {
doSomething() {
if (this.method === Test.prototype.method) {
console.log("Method is native Test's!");
} else {
console.log("Method is not Test's, it's been shadowed!");
}
}
method() {
console.log('parent');
}
}
class A extends Test {
constructor() {
super();
}
method() {
console.log('override');
}
}
new A().doSomething();
new Test().doSomething();
您还可以在Test
的构造函数中进行相同的检查:
class Test {
constructor() {
if (this.method === Test.prototype.method) {
console.log("Method is native Test's!");
} else {
console.log("Method is not Test's, it's been shadowed!");
}
}
method() {
console.log('parent');
}
}
class A extends Test {
constructor() {
super();
}
method() {
console.log('override');
}
}
new A()