Вы можете использовать Object.getPrototypeOf()
, чтобы получить прототип.Затем выполните итерации свойств прототипа, используя for...of
и Object.getOwnPropertyNames()
.Если метод равен одному из методов прототипа, верните true
:
class A {
methodA() {
console.log('method of A');
}
doesMethodBelongHere(method) {
// get the prototype
const proto = Object.getPrototypeOf(this);
// iterate the prototype properties, and if one them is equal to the method's reference, return true
for(const m of Object.getOwnPropertyNames(proto)) {
const prop = proto[m];
if(typeof(prop) === 'function' && prop === method) return true;
}
return false;
}
}
const a = new A();
Object.assign(a, { anotherMethod() {} });
a.anotherMethod2 = () => {};
console.log(a.doesMethodBelongHere(a.methodA)); // should return true
console.log(a.doesMethodBelongHere(a.anotherMethod)); // should return false
console.log(a.doesMethodBelongHere(a.anotherMethod2)); // should return false
Расширенные классы:
Это решение также будет обрабатывать методы, полученные из расширенного класса:
class A {
methodA() {
console.log('method of A');
}
doesMethodBelongHere(method) {
let proto = this;
// iterate the prototypes chain
while (proto = Object.getPrototypeOf(proto), proto && proto !== Object) {
// iterate the prototype properties, and if one them is equal to the method's reference, return true
for (const m of Object.getOwnPropertyNames(proto)) {
const prop = proto[m];
if (typeof(prop) === 'function' && prop === method) return true;
}
}
return false;
}
}
class B extends A {}
class C extends B {}
const c = new C();
Object.assign(c, {
anotherMethod() {}
});
c.anotherMethod2 = () => {};
console.log(c.doesMethodBelongHere(c.methodA)); // should return true
console.log(c.doesMethodBelongHere(c.anotherMethod)); // should return false
console.log(c.doesMethodBelongHere(c.anotherMethod2)); // should return false