Tuesday, December 8, 2015

Javascript Constructor Pattern to Ensure new is Called

Here is a pattern that will ensure "new" is called when defining an object constructor. When calling a JavaScript constructor function, if "new" is not used, then the variable being assigned will be undefined unless the constructor function returns something else.


function Griffen(name){
  this.name = name;
  if(this instanceof Griffen){
    return;
  }
  return new Griffen(name)
}
console.log(Griffen("Pete"));

No comments:

Post a Comment