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