Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created January 24, 2013 00:18
Show Gist options
  • Select an option

  • Save XoseLluis/4616181 to your computer and use it in GitHub Desktop.

Select an option

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.
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