javascript - Nodejs中当前类的实例

标签 javascript node.js instanceof

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

在 PHP 中,它是这样完成的:

if ($obj instanceof self) {

}

nodejs 中的等价物是什么?

最佳答案

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

I want to test if a variable is an instance of the current class. So I'm checking within a method of the class. And I was hoping there's a more abstract way of doing than specifying the class name. In PHP it's possible with the self keyword.

我想说,在这种情况下,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

关于javascript - Nodejs中当前类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52598138/

相关文章:

javascript - 下载取消后重定向至网页

javascript - 如何使用接口(interface)注释嵌套对象以进行配置检查?

javascript - node.js中tls模块的newSession事件返回的session id类型

javascript - Jade - 访问传递给它的变量

javascript - node.js 事件队列在哪里?

java - java中的instanceOf运算符

javascript - 当点向下钻取时获取 Highcharts 中点击点的名称

java - 在 Java 14 与 Java 17 中使用 instanceof

java - 我怎样才能减少这个的圈复杂度?

javascript - 仅当 Angular 从资源对象检索数据时才选择选项元素