Есть ли способ определить, является ли функция методом определенного класса?
У меня есть class A
с методом doesMethodBelongHere
, который принимает функцию как method
аргумента. Я хочу определить, что method
является фактическим методом A
class A {
methodA() {
console.log('method of A');
}
doesMethodBelongHere(method) {
// it should return true if 'method' argument is a method of A
return Object.values(this).includes(method);
}
}
const a = new A();
console.log(a.doesMethodBelongHere(a.methodA)); // should return true
Вы можете использовать Object.getPrototypeOf()
для получения прототипа. Затем выполните итерацию свойств прототипа, используя for...of
и Object.getOwnPropertyNames()
. Если метод равен одному из методов прототипа return 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 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
Я бы предложил использовать следующую реализацию:
A.prototype
, но более общий подход) для повторения методов класса.Используя Array.some, найдите, включает ли (1) имя данного метода.
class A {
constructor() {
this.a = 2;
this.bb = 3;
}
methodA() {
console.log('method of A');
}
doesMethodBelongHere(method) {
// it should return true if 'method' argument is a method of A
return this.constructor.prototype[method.name] === method;
}
}
Вы можете использовать оператор typeof
let isfn = "function" === typeof ( a.methodA );//isfn should be true
isfn = "function" === typeof ( a["methodA"] );//isfn should be true
isfn = "function" === typeof ( a["methodAX"] );//isfn should be false
doesMethodBelongHere( method ) {
return "function" === typeof ( this[method.name] )
}
class A {
constructor() {
this.methodA = this.methodA.bind(this);
this.doesMethodBelongHere = this.doesMethodBelongHere.bind(this);
}
methodA() {
console.log('method of A');
}
doesMethodBelongHere(method) {
// it should return true if 'method' argument is a method of A
return Object.values(this).includes(method);
}
}
const a = new A();
console.log(a.doesMethodBelongHere(a.methodA)); // should return true
Это не было связано с вашим классом в вашем doesMethodBelongHere
.
this
изменилось в момент инстанцирования. Привязка this
к вашему классу сохраняет контекст в нужном месте.