How make “typeof” on extends in Javascript?

2019-09-13 04:07发布

Example:

class Foo extends Bar {

}

Foo typeof Bar //-> false :(

How discover that Foo extend Bar?

2条回答
干净又极端
2楼-- · 2019-09-13 04:22

As ES6 classes inherit prototypically from each other, you can use isPrototypeOf

Bar.isPrototypeOf(Foo) // true

Alternatively just go with the usual instanceof operator:

Foo.prototype instanceof Bar // true
// which is more or (in ES6) less equivalent to
Bar.prototype.isPrototypeOf(Foo.prototype)
查看更多
我只想做你的唯一
3楼-- · 2019-09-13 04:31

MDN for typeof :

The typeof operator returns a string indicating the type of the unevaluated operand

you need 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
查看更多
登录 后发表回答