Skip to content

Instantly share code, notes, and snippets.

@wxactly
Created January 5, 2015 22:07
Show Gist options
  • Save wxactly/997e8394385782b8b476 to your computer and use it in GitHub Desktop.
Save wxactly/997e8394385782b8b476 to your computer and use it in GitHub Desktop.
"Objects-only" prototypal inheritance user-land lib. (Inspired by http://davidwalsh.name/javascript-objects-deconstruction)
Prototype = {
create: function() {
var proto = Object.prototype;
var protoProperties = arguments[0] || {};
if(arguments.length > 1) {
proto = arguments[0];
protoProperties = arguments[1] || {};
}
var prototypeObject = Object.create(proto);
for(var protoProperty in protoProperties) {
prototypeObject[protoProperty] = protoProperties[protoProperty];
}
prototypeObject.create = function(properties) {
properties = properties || {};
var object = Object.create(prototypeObject);
for(var property in properties) {
object[property] = properties[property];
}
return object;
};
return prototypeObject;
}
};
//EXAMPLE
Foo = Prototype.create({
identify: function() {
return "I am " + this.me;
}
});
Bar = Prototype.create(Foo, {
speak: function() {
alert("Hello, " + this.identify() + ".");
}
});
var b1 = Bar.create({me: "b1"});
var b2 = Bar.create({me: "b2"});
b1.speak(); // alerts: "Hello, I am b1."
b2.speak(); // alerts: "Hello, I am b2."
//ALTERNATE PATTERN
Foo.init = function(who) {
this.me = who;
return this;
};
var b3 = Bar.create().init("b3");
b3.speak(); // alerts: "Hello, I am b3."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment