JSFiddle - React, Tailwind, and code Playground
HTML
<h2>How to avoid using new on Constructors</h2>
<p>The trick is to return check if the `this` variable is an instanceof of the Constructor. If not, then return a new instance of the constructor whiling passing the same arguments. `new ConstructorName(arg1, arg2, ... argN)`.</p>
JavaScript
// Written by Larry Battle <bateru.com/news>
var log = function(str){
document.body.innerHTML += "<br/>" + str;
}
var name = "\'global name\'";
var Person = function( name ){
if(!(this instanceof Person)){
return new Person(name);
}
this.name = name || "NA" ;
return this;
};
var a = new Person( "Tom" );
log( "a = new Person( 'Tom' )" );
log( "global name = " + name );
log( "a.name = " + a.name );
log( "" );
var b = Person( "Bob" );
log( "b = Person('Bob')" );
log( "global name = " + name );
log( "b.name = " + b.name );
log( "" );
var c = Person();
log( "c = Person() makes global name = " + name );
log( "c.name = " + c.name );