Javascript 检查函数是否是类的方法?

Javascript 检查函数是否是类的方法?,javascript,ecmascript-6,Javascript,Ecmascript 6,有没有办法确定函数是否是某个类的方法 我有一个类,它有一个方法doesmethodbelong,该方法将函数作为参数方法。我想确定method是A的实际方法 A类{ 方法a(){ log(“A的方法”); } doesMethodBelongHere(方法){ //如果'method'参数是 返回Object.values(this.includes)(方法); } } 常数a=新的a(); console.log(a.doesMethodBelongHere(a.methodA));//应返

有没有办法确定函数是否是某个类的方法

我有一个
,它有一个方法
doesmethodbelong
,该方法将函数作为参数
方法
。我想确定
method
A
的实际方法

A类{
方法a(){
log(“A的方法”);
}
doesMethodBelongHere(方法){
//如果'method'参数是
返回Object.values(this.includes)(方法);
}
}
常数a=新的a();
console.log(a.doesMethodBelongHere(a.methodA));//应返回true
A类{
构造函数(){
this.methodA=this.methodA.bind(this);
this.doesMethodBelongHere=this.doesMethodBelongHere.bind(this);
}
方法a(){
log(“A的方法”);
}
doesMethodBelongHere(方法){
//如果'method'参数是
返回Object.values(this.includes)(方法);
}
}
常数a=新的a();
console.log(a.doesMethodBelongHere(a.methodA));//应该返回true
,您可以使用它来获取原型。然后使用和迭代原型属性。如果该方法等于原型上的方法之一,则返回
true

A类{
方法a(){
log(“A的方法”);
}
doesMethodBelongHere(方法){
//得到原型
const proto=Object.getPrototypeOf(this);
//迭代原型属性,如果其中一个属性等于方法的引用,则返回true
for(对象的常量m.getOwnPropertyNames(proto)){
常数prop=proto[m];
if(typeof(prop)=='function'&&prop==method)返回true;
}
返回false;
}
}
常数a=新的a();
赋值(a,{anotherMethod(){}});
a、 anotherMethod2=()=>{};
console.log(a.doesMethodBelongHere(a.methodA));//应该返回true
console.log(a.doesMethodBelongHere(a.anotherMethod));//应该返回false

console.log(a.doesMethodBelongHere(a.anotherMethod2));//如果返回false,则可以使用
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
编辑
我建议使用以下实现:

  • 在构造函数原型上使用(与访问
    A.prototype
    相同,但采用更通用的方法),以迭代类方法
  • 使用获取方法名
  • 使用,查找(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;
        }
    }
    

  • @Liam的可能副本与此副本的副本距离不远。@Liam Linked duplicate提出了一个一般性问题,“此方法是否存在?”-OP提出的问题是,“如何确认a是B类的方法?”。如果它是a的特定实例的方法,则应返回true?还是一般的a类方法?@ReuvenChacha
    一般的a类方法
    你能详细说明一下吗?在没有显式绑定的情况下可以实现吗?
    这个
    在实例化时发生了移动。将
    this
    绑定到您的类可以将上下文保持在正确的位置。但是我将引用传递给函数,诀窍是获取其名称。方法名称等效并不意味着相同的方法。
    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;
        }
    }