javascriptconstructorthisinstanceof

Why would a JavaScript function check if `this` is `instanceof` that same function?


What I think this is doing is looking to see if this object has already been instantiated and exists within the scope? Why do we need to use a triple equal sign to determine?

function viewmodel(parent) {
  if (false === (this instanceof viewmodel)) {
    return new viewmodel(parent);
  }

  // ...
}

Solution

  • You don't need a strict equality comparison there. instanceof yields true or false, so this is entirely sufficient:

    if (!(this instanceof viewmodel))