Skip to content

Instantly share code, notes, and snippets.

@tobie
Created January 4, 2009 14:15
Show Gist options
  • Save tobie/43064 to your computer and use it in GitHub Desktop.
Save tobie/43064 to your computer and use it in GitHub Desktop.
/*
Simpler, more robust super keyword for Prototype.
Given the following parent class:
var Person = Class.create({
initialize: function(name) {
this.name = name;
},
say: function(message) {
return this.name + ': ' + message;
}
});
Subclassing with Class#callSuper:
var Pirate = Class.create(Person, {
say: function(message) {
return this.callSuper('say', message) + ', yarr!';
}
});
... and using Class#applySuper, you can directly pass the arguments object:
var Pirate = Class.create(Person, {
say: function() {
return this.applySuper('say', arguments) + ', yarr!';
}
});
Of course this also allows calling other methods of the subclass (Whether this is a good or a bad thing is a whole other topic).
var Pirate = Class.create(Person, {
say: function() {
return this.applySuper('say', arguments) + ', yarr!';
},
yell: function(message) {
return this.callSuper('say', message.toUpperCase());
}
});
*/
(function() {
var slice = Array.prototype.slice;
function callSuper(methodName) {
return this.applySuper(methodName, slice.call(arguments, 1));
}
function applySuper(methodName, args) {
return this.constructor.superclass.prototype[methodName].apply(this, args);
}
return {
callSuper: callSuper,
applySuper: applySuper
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment