Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created April 16, 2012 10:40
Show Gist options
  • Save icodejs/2397617 to your computer and use it in GitHub Desktop.
Save icodejs/2397617 to your computer and use it in GitHub Desktop.
Create JS object
/*
Similarly to the classical Holy Grail, you would use an empty temporary
constructor function F(). You then set the prototype of F() to be the parent
object. Finally, you return a new instance of the temporary constructor:
*/
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
/*
Classical inheritance to a language without classes
A function similar to this exists in the YUI library (and probably other libraries) and
brings the , if you decide that this is
the best approach for your project.
This pattern is also referred to as one using a proxy function or a proxy
constructor, instead of a temporary constructor, because the temporary
constructor is used as a proxy to get to the parent’s prototype.
*/
function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
/*
You can use an immediate function and store the proxy
function in its closure:
*/
var inherit = (function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment