Skip to content

Instantly share code, notes, and snippets.

@puffnfresh
Created March 29, 2013 02:04
Show Gist options
  • Save puffnfresh/5268263 to your computer and use it in GitHub Desktop.
Save puffnfresh/5268263 to your computer and use it in GitHub Desktop.
Two nice helper functions for creating constructors in JavaScript.
// Polyfill for Object.create
function create(proto) {
function Ctor() {}
Ctor.prototype = proto;
return new Ctor();
}
// Always returns an instance of constructor
function getInstance(self, constructor) {
return self instanceof constructor ? self : create(constructor.prototype);
}
// Our custom constructor
function Container(value) {
var self = getInstance(this, Container);
self.value = value;
return self;
}
var a = new Container(100);
var b = Container(100);
console.log(a.value); // 100
console.log(b.value); // 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment