【问题标题】:How make "typeof" on extends in Javascript?如何在Javascript中扩展“typeof”?
【发布时间】:2023-03-09 23:35:01
【问题描述】:

例子:

class Foo extends Bar {

}

Foo typeof Bar //-> false :(

如何发现Foo 扩展Bar

【问题讨论】:

  • 你需要instanceof 而不是typeof

标签: javascript ecmascript-6 babeljs


【解决方案1】:

由于 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)

【讨论】:

    【解决方案2】:

    typeof 的 MDN:

    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
    

    【讨论】:

    • 这需要创建一个实例,这可能会产生不希望的副作用。我认为他想从功能本身来做到这一点。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2019-10-19
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多