I recently delved into the world of JavaScript Patterns through Stoyan Stefanov's book. One pattern that caught my attention involves enforcing the use of the new operator for constructor functions, demonstrated with the following code snippet:
function Waffle() {
if (!(this instanceof Waffle)) {
return new Waffle();
}
this.tastes = "yummy";
}
Waffle.prototype.wantAnother = true;
This structure allows you to invoke the Waffle function in two different ways:
var first = new Waffle(),
second = Waffle();
I found this approach quite useful and began brainstorming a method that I could easily incorporate into any constructor function without the need for manual adjustments each time.
Here's what I came up with:
function checkInstance (name) {
if (name.constructor.name === undefined) {
return "construct it"
} else {
return false;
}
}
function Waffle() {
var _self = checkInstance.call(this, this);
if (_self === "construct it") {
return new Waffle()
}
this.tastes = "yummy"
}
var waffle = Waffle()
waffle
By implementing this approach, I can now call the Waffle function using both new Waffle or Waffle(), ensuring consistency in object creation.
However, I've encountered a stumbling block here:
if (_self === "construct it") {
return new Waffle()
}
I'm wondering if there is a way to reference new Waffle()
without explicitly mentioning the function name, allowing for a more generic implementation. Essentially, can I save Waffle() as a variable and use something like:
return new var
Unfortunately, using properties like this.name doesn't seem feasible until invoked.
If anyone has thoughts on a possible solution or alternative approach, I would greatly appreciate your feedback. Thank you!