Object construction: check if this is an instance of an Object

I saw this test in the vendor code object constructors:

function MyObject() {
  if (!(this instanceof MyObject)) return new MyObject;
  ...
}

My first slope is that this test is used to prevent binding to another value thiswhen calling the constructor. However, I wanted to check here that there is something else that I am missing. Can someone explain the specific intent of this test?

+3
source share
1 answer

This test should ensure that it is MyObjectalways used as a constructor, namely:

var instance = new MyObject();

and never

var instance = MyObject();

leading to undesired code behavior.

- var instance = MyObject();, this (Window) instanceof check .

, . , , .

+7

All Articles