如何检查一个JavaScript类是否继承了另一个(不创建对象)?

roejwanj  于 2023-08-02  发布在  Java
关注(0)|答案(7)|浏览(124)

例如:

function A(){}
function B(){}
B.prototype = new A();

字符串
如何检查类B是否继承了类A?

nvbavucw

nvbavucw1#

请尝试以下操作:

ChildClass.prototype instanceof ParentClass

字符串

dzjeubhm

dzjeubhm2#

测试直接继承

B.prototype.constructor === A

字符串
要测试间接继承,您可以用途:

B.prototype instanceof A

  • (第二个解决方案由Nirvana Tikku首次给出)*
y3bcpkx1

y3bcpkx13#

回到2017年:
检查一下是否适合你

ParentClass.isPrototypeOf(ChildClass)

字符串
如果您希望防止阴影,请选择以下选项:

const isPrototypeOf = Function.call.bind(Object.prototype.isPrototypeOf);

// Usage:
isPrototypeOf(ParentClass, ChildClass); // true or false

xurqigkl

xurqigkl4#

**Gotchas:**注意,如果使用多个执行上下文/窗口,instanceof不会按预期工作。参见§§。

此外,根据https://johnresig.com/blog/objectgetprototypeof/,这是与instanceof相同的替代实现:

function f(_, C) { // instanceof Polyfill
  while (_ != null) {
    if (_ == C.prototype)
      return true;
    _ = _.__proto__;
  }
  return false;
}

字符串
修改它以直接检查类,我们可以得到:

function f(ChildClass, ParentClass) {
  _ = ChildClass.prototype;
  while (_ != null) {
    if (_ == C.prototype)
      return true;
    _ = _.__proto__;
  }
  return false;
}

侧记

instanceof本身检查obj.proto是否为f.prototype,因此:

function A(){};
A.prototype = Array.prototype;
[]instanceof Array // true


以及:

function A(){}
_ = new A();
// then change prototype:
A.prototype = [];
/*false:*/ _ instanceof A
// then change back:
A.prototype = _.__proto__
_ instanceof A //true


以及:

function A(){}; function B(){};
B.prototype=Object.prototype;
/*true:*/ new A()instanceof B


如果不相等,则在检查中将proto与proto的proto交换,然后是proto的proto的proto的proto,依此类推。因此:

function A(){}; _ = new A()
_.__proto__.__proto__ = Array.prototype
g instanceof Array //true


以及:

function A(){}
A.prototype.__proto__ = Array.prototype
g instanceof Array //true


以及:

f=()=>{};
f.prototype=Element.prototype
document.documentElement instanceof f //true
document.documentElement.__proto__.__proto__=[];
document.documentElement instanceof f //false

gpnt7bae

gpnt7bae5#

它在类(B)和类示例(b)之间是不同的...

function A(){}
function B(){}
B.prototype = new A();
const b = new B();

console.log(B.prototype instanceof A);
// true
console.log(Object.getPrototypeOf(b) instanceof A);
// true

字符串
同样

class E extends Error {}
const e = new E();

console.log(E.prototype instanceof Error);
// true
console.log(e.constructor.prototype instanceof Error);
// true
console.log(Object.getPrototypeOf(e) instanceof Error);
// true

zaq34kh6

zaq34kh66#

我不认为Simon在他的问题中指的是B.prototype = new A(),因为这肯定不是在JavaScript中链接原型的方式。
假设B扩展A,使用Object.prototype.isPrototypeOf.call(A.prototype, B.prototype)

ss2ws0br

ss2ws0br7#

其他人对我来说都很有用。ChatGPT也不行。我用下面的代码解决了。

/**
 * Checks whether a given object is inherited from a specified superclass.
 * 
 * @param {Object} object - The object to check.
 * @param {Function} superClass - The superclass to compare against.
 * @returns {boolean} - True if the object is a subclass of the superclass, false otherwise.
 */
isInheritedFrom(object, superClass) {
    console.log(`Checking if ${object.constructor.name} is a subclass of ${superClass.name}`);
    
    let currentProto = Object.getPrototypeOf(object.constructor);

    while (currentProto) {
        if (currentProto.name === superClass.name) {
            console.log(`Found match for a superclass of ${object.constructor.name} with ${superClass.name}`);
            // object is a subclass of the superclass
            return true;
        }
        currentProto = Object.getPrototypeOf(currentProto);
    }
    
    console.log(`No match found for ${object.constructor.name} with ${superClass.name}`);
    // object is not a subclass of the superclass
    return false;
}

字符串

相关问题