Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

javascript - Check if a constructor inherits another in ES6

I have a situation where I need to check if a constructor (X) has another constructor (Y) in its prototype chain (or is Y itself).

The quickest means to do this might be (new X()) instanceof Y. That isn't an option in this case because the constructors in question may throw if instantiated without valid arguments.

The next approach I've considered is this:

const doesInherit = (A, B) => {
  while (A) {
    if (A === B) return true;
    A = Object.getPrototypeOf(A);
  }

  return false;
}

That works, but I can't shake the sense that I'm missing some more straightforward way to check this. Is there one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because of the way instanceof works, you should be able to do

A.prototype instanceof B

But this would only test inheritance, you should have to compare A === B to test for self-reference:

A === B || A.prototype instanceof B

Babel example:

class A {}
class B extends A {}
class C extends B {}

console.log(C === C) // true
console.log(C.prototype instanceof B) // true
console.log(C.prototype instanceof A) // true

instanceof is basically implemented as follows:

function instanceof(obj, Constr) {
  var proto;
  while ((proto = Object.getProtoypeOf(obj)) {
    if (proto === Constr.prototype) {
      return true;
    }
  }
  return false;
}

It iterates over the prototype chain of the object and checks whether any of the prototypes equals the constructors prototype property.

So almost like what you were doing, but internally.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...