Created
March 29, 2013 02:04
-
-
Save puffnfresh/5268263 to your computer and use it in GitHub Desktop.
Two nice helper functions for creating constructors in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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