【发布时间】:2023-03-09 23:35:01
【问题描述】:
例子:
class Foo extends Bar {
}
Foo typeof Bar //-> false :(
如何发现Foo 扩展Bar?
【问题讨论】:
-
你需要
instanceof而不是typeof
标签: javascript ecmascript-6 babeljs
例子:
class Foo extends Bar {
}
Foo typeof Bar //-> false :(
如何发现Foo 扩展Bar?
【问题讨论】:
instanceof 而不是typeof
标签: javascript ecmascript-6 babeljs
由于 ES6 类是相互继承原型的,你可以使用isPrototypeOf
Bar.isPrototypeOf(Foo) // true
或者使用通常的instanceof operator:
Foo.prototype instanceof Bar // true
// which is more or (in ES6) less equivalent to
Bar.prototype.isPrototypeOf(Foo.prototype)
【讨论】:
typeof 的 MDN:
typeof 操作符返回一个字符串,表示类型 未计算的操作数
你需要instanceof,isPrototypeOf
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
【讨论】: