Created
January 4, 2009 14:15
-
-
Save tobie/43064 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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