Skip to content

Instantly share code, notes, and snippets.

@michaelBenin
Created January 24, 2015 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelBenin/8c4e28f9aa4cacc543e3 to your computer and use it in GitHub Desktop.
Save michaelBenin/8c4e28f9aa4cacc543e3 to your computer and use it in GitHub Desktop.
Extending underscore to extend objects' functions with this._super
// Description:
// Adds this._super method to objects that are extended and have the
// same function, keeps original function as reference on this._super
var _ = require('underscore');
_.extendWithSuper = function(obj) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
// check to see if both methods are functions
if(_.isFunction(source[prop]) && _.isFunction(obj[prop])){
var Class = function(){
this._super = obj[prop];
};
var tmpClass = new Class();
obj[prop] = function(){
return source[prop].apply(tmpClass, _.toArray(arguments));
};
obj[prop].prototype = source[prop].prototype;
} else {
obj[prop] = source[prop];
}
}
}
}
return obj;
};
var events = {
click: function(){
console.log('clicked original');
}
};
var events2 = {
click: function(){
this._super();
console.log('clicked inherited');
}
};
var events3 = _.extendWithSuper(events, events2);
events3.click();
// clicked original
// clicked inherited
// undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment