Skip to content

Instantly share code, notes, and snippets.

@sehrgut
Created April 30, 2013 03:42
Show Gist options
  • Save sehrgut/5486479 to your computer and use it in GitHub Desktop.
Save sehrgut/5486479 to your computer and use it in GitHub Desktop.
Notes in search of the One True Javascript Inheritance Pattern, ideally with minimal boilerplate and no helper functions.
// http://www.bennadel.com/blog/2184-Object-create-Improves-Constructor-Based-Inheritance-In-Javascript-It-Doesn-t-Replace-It.htm
var SuperType = function () {
};
SuperType.prototype = {};
var SubType = function () {
this.uber = SuperType;
uber.call(this);
};
SubType.prototype = Object.create(SubType.uber.prototype);
// prototypal inheritance pattern: One True?
var SubTypeTwo = (function (uber) {
function Constructor () {
uber.call(this);
this.uber = uber; // if uber should be exposed
}
Constructor.prototype = Object.create(uber.prototype);
Constructor.protytpe.foo = "bar";
return Constructor;
})(SuperType);
// Other Ideas
var NoPrivateStaticConstructor = function () {
var privateField;
function privateMethod () {}
var privateMethodTwo = function () {};
this.privilegedMethod = function () {};
this.privilegedMethodFromPrivate = privateMethod;
};
NoPrivateStaticConstructor.prototype = {
publicMethod: function () {},
publicCopyOnWriteField: "foo";
};
NoPrivateStaticConstructor.publicStaticField = "bar";
var ObjectConstructor = (function () { // closure to support private static scope
var privateStaticField = "I am static and private.";
function privateStaticMethod () { "I am a priviate static method, and can access public and private static fields."; }
var Constructor function () {
// The constructor function as normal
this.privilegedInstanceMethod = function () { "I am a privileged instance method, and can access public and private instance and static fields."; };
function privateInstanceMethod = function () { "I am a private instance method, and can access public and private instance and static fields."; };
this.privateInstanceMethodExposed = privateInstanceMethod; // exposing a private instance method as privileged
};
Constructor.publicStaticField = "I am static and public.";
Constructor.prototype = {
prototypeField: "I am a copy-on-write prototype field.",
publicInstanceMethod: function () { "I am a public instance method, and can't access private instance fields, but can access private static fields."; }
};
return Constructor;
})();
ObjectConstructor.publicStaticFieldTwo = "I am also static and public.";
var ChildConstructor = function () {};
ChildConstructor.prototype = new ObjectConstructor();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment