nodejs 中的当前实例 class
Instanceof current class in nodejs
我想测试一个变量是否是当前 class 的一个实例。所以我正在检查 class 的方法。我希望有比指定 class 名称更抽象的方法。在 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
我想测试一个变量是否是当前 class 的一个实例。所以我正在检查 class 的方法。我希望有比指定 class 名称更抽象的方法。在 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