PythonIsGreat
PythonIsGreat

Reputation: 7887

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);
  }

  // ...
}

Upvotes: 2

Views: 84

Answers (2)

Pudd
Pudd

Reputation: 447

The triple equals prevents implicit datatype conversion.

See this question for more information.

Upvotes: 2

JMM
JMM

Reputation: 26787

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

if (!(this instanceof viewmodel))

Upvotes: 5

Related Questions