代码之家  ›  专栏  ›  技术社区  ›  Alex

nodejs中当前类的实例

  •  1
  • Alex  · 技术社区  · 6 年前

    在PHP中是这样做的:

    if ($obj instanceof self) {
    
    }
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   zero298    6 年前

    考虑到你的意见(我的):

    我想测试一个变量是否是 . 所以呢 我在查 在类的方法中 . 我希望有一个 比指定类名更抽象的方法。在PHP中是 可能与 关键字。

    self 在这种情况下 this.constructor

    class Foo {}
    class Bar {}
    class Fizz {
      // Member function that checks if other 
      // is an instance of the Fizz class without 
      // referring to the actual classname "Fizz"
      some(other) {
        return other instanceof this.constructor;
      }
    }
    
    const a = new Foo();
    const b = new Foo();
    const c = new Bar();
    const d = new Fizz();
    const e = new Fizz();
    
    console.log(a instanceof b.constructor); // true
    console.log(a instanceof c.constructor); // false
    console.log(d.some(a)); // false
    console.log(d.some(e)); // true