Hello

I'm Ricardo, a full-stack human

Scope safe constructors

Our goal is to identify when the constructor was called without the new operator and then invoke the constructor properly. Observe the following code.

function CarPart(name) {
  if(this instanceof CarPart) {
    this.name = name;
  } else {
    return new CarPart(name);
  }
}

In this code, we evaluate if the this object is a CarPart and proceed as normal. If the this object is not a CarPart (ie, it's a window object), call the constructor again, this time with the new operator.

Now our constructor works properly with or without the new operator.