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.
In PHP it's done like this:
if ($obj instanceof self) {
}
What's the equivalent in nodejs ?
Considering your comment (emphasis mine):
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.
I would say that self
in this instance would kind of map to this.constructor
. Consider the following:
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