title: JavaScript class: (instanceof this)
body: <p>I want to check if an object is an instance of the current class
  it works fine from outside the class, but gives error if I called it from inside the class</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>class test {
  
    check(obj) {
      return (obj instanceof this) //error: this is not a function
  
    }
  }
  
  
  const obj = new test()
  
  console.log(obj instanceof test) //true
  console.log(new test().check(obj)) //ERROR</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>Solving:</strong></p>
  
  <p><em>method #1: (by: <a href="https://stackoverflow.com/a/53204052/9474643">@CertainPerformance</a> )</em>
  we cannot use: return obj instanceof this,</p>
  
  <p>because (this) is an object (i.e: obj instanceof OBJECT),</p>
  
  <p>so we can use the constractor object:</p>
  
  <pre><code>return obj instanceof this.constructor
  </code></pre>
  
  <p><em>method #2: (by: <a href="https://stackoverflow.com/a/53204057/9474643">@Matías Fidemraizer</a> )</em>  </p>
  
  <pre><code>   return Object.getPrototypeOf(this).isPrototypeOf () //using this-&gt;better 
  
     //or: className.prototype.isPrototypeOf (obj) 
        //if you know the class name and there is no intent to change it later
  </code></pre>
  
  <p>method #3: (by: <a href="https://stackoverflow.com/a/53205865/9474643">@Thomas</a> )
  make the function "check" static</p>
  
  <pre><code>static check(obj) {
      // now `this` points to the right object, the class/object on which it is called,        
      return obj instanceof this;
    }
  </code></pre>