【问题标题】:Instanceof current class in nodejsnodejs中当前类的实例
【发布时间】:2018-10-01 20:05:43
【问题描述】:

我想测试一个变量是否是当前类的实例。所以我在类的一个方法中检查。我希望有一种比指定类名更抽象的方法。在 PHP 中,可以使用 self 关键字。

在 PHP 中是这样完成的:

if ($obj instanceof self) {

}

nodejs 中的等价物是什么?

【问题讨论】:

标签: javascript node.js instanceof


【解决方案1】:

考虑到您的评论(强调我的):

我想测试一个变量是否是当前类的实例。所以 我正在检查类的方法。我希望有一个 比指定类名更抽象的做法。在 PHP 中是 可以使用 self 关键字。

我想说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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2021-01-25
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多