2

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 ?

8
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – user5734311
    Commented Oct 1, 2018 at 20:07
  • How doesn't Google answer this
    – Greggz
    Commented Oct 1, 2018 at 20:09
  • Possible duplicate of How to test same object instance in Javascript?
    – Ruzihm
    Commented Oct 1, 2018 at 20:09
  • 1
    Perhaps you're looking for thing instanceof this.constructor.
    – CRice
    Commented Oct 1, 2018 at 20:14
  • 3
    You didn't specify the context for this code. But in case it's executed in instance method, then this is as previous comment says. This is not specific to instanceof. Current class can be referred as this in static methods and as this.constructor in instance methods. Commented Oct 1, 2018 at 20:21

1 Answer 1

2

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.