如何在 Javascript 中扩展 “typeof”

How make "typeof" on extends in Javascript?

本文关键字:typeof 扩展 Javascript      更新时间:2023-09-26

示例:

class Foo extends Bar {
}
Foo typeof Bar //-> false :(

如何发现Foo扩展Bar

由于 ES6 类彼此继承原型,因此您可以使用isPrototypeOf

Bar.isPrototypeOf(Foo) // true

或者,只需使用通常的instanceof运算符:

Foo.prototype instanceof Bar // true
// which is more or (in ES6) less equivalent to
Bar.prototype.isPrototypeOf(Foo.prototype)

MDN for typeof

typeof 运算符返回一个字符串,指示 未计算的操作数

你需要instanceofisPrototypeOf

class Bar{}
class Foo extends Bar {}
var n  = new Foo();
console.log(n instanceof Bar); // true
console.log(Bar.isPrototypeOf(Foo)); // true
console.log(Foo.prototype instanceof Bar); // true