Created
January 24, 2013 00:18
-
-
Save XoseLluis/4616181 to your computer and use it in GitHub Desktop.
Lazy Object Construction in JavaScript. Create Lazy versions (unitialized) of your objects, and let the consumer initialize them right when he really needs them.
This file contains hidden or 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
| function Lazy(type){ | |
| var _arguments = [].slice.call(arguments, 1); | |
| this.create = function(){ | |
| var inst = Object.create(type.prototype); | |
| //need this extra inst2 to follow the correct behaviour in case the constructor returns something | |
| var inst2 = type.apply(inst, _arguments); | |
| return inst2 || inst; | |
| }; | |
| } | |
| //usage: | |
| var p = new Lazy(Person, "Xuan", 37); | |
| //first time the consumer checks whether the object has been created | |
| p = p instanceof Lazy ? p.create() : p; | |
| //further on we can use it as a normal object | |
| console.log(p.sayHi()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment