Skip to content

Instantly share code, notes, and snippets.

@passcod
Last active December 21, 2015 17:29
Show Gist options
  • Select an option

  • Save passcod/6340848 to your computer and use it in GitHub Desktop.

Select an option

Save passcod/6340848 to your computer and use it in GitHub Desktop.
JavaScript version of https://gist.github.com/passcod/6340716, compiled and then made prettier by hand.
Namespace.extend = function(src, obj) {
if (obj == null) {
obj = {};
}
var newObj;
if (typeof obj.init === 'function') {
newObj = obj.init;
delete obj.init;
} else {
newObj = function() {};
}
newObj.prototype = Object.create(src.prototype);
newObj.prototype.constructor = newObj;
for (var prop in obj) {
newObj.prototype[prop] = obj[prop];
}
var props = {};
Object.keys(src).forEach(function(prop) {
props[prop] = Object.getOwnPropertyDescriptor(src, prop);
});
['create', 'extend'].forEach(function(prop) {
(function(func, self) {
props[func] = Object.getOwnPropertyDescriptor(Namespace, func);
props[func].value = function() {
var args = [].slice.call(arguments);
args.unshift(self);
return Namespace[func].apply(this, args);
};
})(prop, newObj);
});
Object.defineProperties(newObj, props);
return newObj;
};
Namespace.create = function(src, obj, init) {
var newObj = src.extend(obj);
return new newObj(init);
};
Namespace.Object = Namespace.extend(function() {});
var Actor = Namespace.Object.extend({
act: function() {
// and he stepeth and speaketh
},
canSpeak: true
});
var MuteActor = Actor.extend({
canSpeak: false
});
Actor.act //=> undefined
(new Actor).act //=> function
(new Actor).canSpeak //=> true
(new MuteActor).canSpeak //=> true
(new Actor) instanceof Namespace.Object //=> true
(new MuteActor) instanceof Actor //=> true
(new MuteActor) instanceof Namespace.Object //=> true
(new Actor) instanceof MuteActor //=> false
var CustomConstructor = Namespace.Object.extend({
init: function() {
console.log('Yippy!');
}
});
new CustomConstructor //$> 'Yippy!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment