Skip to content

Instantly share code, notes, and snippets.

@bttmly
Last active August 29, 2015 14:12
Show Gist options
  • Save bttmly/c4a22e37941c3dba8b26 to your computer and use it in GitHub Desktop.
Save bttmly/c4a22e37941c3dba8b26 to your computer and use it in GitHub Desktop.
instanceof w prototypal instantiation

Using object constructors that require new is something of an anti-pattern, despite being very well established. Numerous posts and questions address this topic. Generally, objections to new come in one of a few flavors:

  • It masks the underlying prototypal inheritance mechanism by borrowing terminology from classical OO. The "JavaScripty" way is to embrace prototypal inhertiance, rather than use misleading sugar like new (or the upcoming es6 class syntax).
  • It tightly couples clients to the constructor implementation.
  • It is dangerous in that a function intended to be called with new may spam the global namespace when called without new.
  • It makes it awkward to do things like partial application, or use an array of arguments with .apply

However, it's fairly straightforward to write factory functions -- object-building functions intended to be called without new -- that still support calling with new and even properly identify produced objects as instanceof the factory. As such, consumers are free to use these functions however they please. Perhaps they prefer the way capitalized constructors and new appear in their specific editor and syntax highlighting; that's fine. They can simply

var Hello = require("helloFactory"); 
var hi = new Hello();`

Alternately, they can do:

var helloFactory = require("helloFactory");
var hi = helloFactory();
var helloProto = {
toString: function () {
return "Hello!";
}
}
function helloFactory () {
return Object.create(helloProto);
}
helloFactory.prototype = helloProto;
var hello1 = helloFactory();
var hello2 = new helloFactory();
hello1 instanceof helloFactory // true
hello2 instanceof helloFactory // true
var helloInheritorProto = Object.create(helloFactory.prototype);
helloInheritorProto.sayHi = function () {
return "Hi!";
}
function helloInheritorFactory () {
return Object.create(helloInheritorProto);
}
helloInheritorFactory.prototype = helloInheritorProto;
var hello3 = helloInheritorFactory();
hello3 instanceof helloInheritorFactory // true
hello3 instanceof helloFactory // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment