Skip to content

Instantly share code, notes, and snippets.

@reu
Last active December 19, 2015 12:49
Show Gist options
  • Save reu/5957962 to your computer and use it in GitHub Desktop.
Save reu/5957962 to your computer and use it in GitHub Desktop.
Function.prototype.addMethod = function(name, method) {
var existingMethod = this.prototype[name];
this.prototype[name] = function() {
if (method.length == arguments.length) {
return method.apply(this, arguments);
} else if (typeof existingMethod == "function") {
return existingMethod.apply(this, arguments);
}
}
}
var assert = console.assert || require("assert").ok;
function Car() {
this.velocity = 10;
}
Car.addMethod("run", function(){
return "Running at " + this.velocity;
});
Car.addMethod("run", function(velocity) {
return "Running at " + velocity;
});
Car.addMethod("stop", function() {
return "Stopped";
});
Car.addMethod("stop", function(seconds) {
return "Stopping in " + seconds + " seconds";
});
function SuperCar() {
Car.apply(this, arguments);
}
SuperCar.prototype = Object.create(Car.prototype);
SuperCar.prototype.constructor = SuperCar;
SuperCar.addMethod("run", function(velocity) {
return "Running at " + velocity * 2;
});
SuperCar.addMethod("run", function(velocity, distance) {
return "Running at " + velocity * 2 + " for " + distance;
});
var car = new Car;
var superCar = new SuperCar;
assert(car.run() == "Running at 10", "Car run no arguments");
assert(car.run(20) == "Running at 20", "Car run with one argument");
assert(superCar.run() == "Running at 10", "SuperCar inheriting the run with no arguments");
assert(superCar.run(20) == "Running at 40", "SuperCar overwriting the run with one argument");
assert(superCar.run(20, 3) == "Running at 40 for 3", "SuperCar creating a new overloaded method");
assert(typeof car.run(20, 30) == "undefined", "Car should not know the new overloaded method");
assert(superCar.stop() == "Stopped", "Inheritance of methods");
assert(superCar.stop(10) == "Stopping in 10 seconds", "Inheritance of overloaded methods");
function Car() {
this.velocity = 10;
}
Car.addMethod("run", function() {
return "Running at " + this.velocity;
});
Car.addMethod("run", function(velocity) {
return "Running at " + velocity;
});
Car.addMethod("run", function(velocity, distance) {
return "Running at " + velocity + " for " + distance + "km";
});
var car = new Car;
car.run() // "Running at 10"
car.run(20) // "Running at 20"
car.run(30, 3) // "Running at 30 for 3km"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment