ES6 detect if a function is on prototype chain of a class instance

Viewed 142

Given an ES6 class:

class C {
  x () { }
  fnIsMethodOfC (fn) { return /* ? */ }
}

and a variety of functions such as

function y () {}
z = () => {}

Is there an efficient way to determine if a function is a method of C i.e.

c = new C()
c.fnIsMethodOfC(c.x) === true
c.fnIsMethodOfC(C.prototype.x) === true
c.fnIsMethodOfC(y) === false
c.fnIsMethodOfC(z) === false

I know one could recursively loop through the prototype chain, but that would be an expensive operation.

Linking related questions:

2 Answers

One option may be:

class C {
  fnIsMethodOfC (fn) {
    const proto = Object.getPrototypeOf(this)
    return proto && proto[fn.name] === fn
  }
}
class C {
  fnIsMethodOfC (fn) {
    if(!fn || !fn.name) return false;
    return !!this[fn.name] && fn === this[fn.name];
  }
}

This will also add addtional check if the actual function is different.

Related