有没有办法确定一个函数是否是某个类的方法?
我有一个带有方法class A
的{{1}},该方法采用函数作为参数doesMethodBelongHere
。我想确定method
是method
的实际方法。
A
答案 0 :(得分:3)
您可以使用Object.getPrototypeOf()
来获取原型。然后使用for...of
和Object.getOwnPropertyNames()
迭代原型属性。如果该方法等于原型上的方法之一,则返回dashboards_button = driver.find_element_by_css_selector(".REPORTING_DASHBOARDS__link.navMenuLabel")[1]
dashboards_button.click()
:
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
答案 1 :(得分:1)
您可以使用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] )
}
答案 2 :(得分:0)
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
中的班上。
答案 3 :(得分:0)
我建议使用以下实现:
<h1> </h1>
<h2> </h2>
<h3> </h3>
<h4> </h4>
<h5> </h5>
<h6> </h6>
<div class="popup901" onclick="myFunction901()"> Teams
<span class="popuptext901" id="myPopup901">2016, 2018: 22</span>
</div>
,但使用更通用的方法),以迭代类方法。使用Array.some,查找(1)是否包括给定方法的名称。
A.prototype