Ruby's Module#remove_method and inheritance in JavaScript
This article follows Ruby's open classes and inheritance in JavaScript and shows that the simple extend function gives us the ability to simulate Ruby's Module#remove_method. Below are Ruby and JavaScript versions to show this at work.
Ruby
class Person
def initialize(first, last)
@first = first
@last = last
end
def reverse
@last + ', ' + @first
end
end
class Employee < Person
def initialize(first, last, id)
super(first, last)
@id = id
end
def reverse
super + ': ' + @id.to_s
end
end
peter = Employee.new('Peter', 'Michaux', 3)
puts peter.reverse # Michaux, Peter: 3
class Employee
remove_method :reverse
end
puts peter.reverse # Michaux, Peter
JavaScript
var Class = {
extend: function(subclass, superclass) {
function D() {}
D.prototype = superclass.prototype;
subclass.prototype = new D();
subclass.prototype.constructor = subclass;
subclass.superclass = superclass;
subclass.superproto = superclass.prototype;
}
};
function Person(first, last) {
this.first = first;
this.last = last;
}
Person.prototype.reverse = function() {
return this.last + ', ' + this.first;
};
function Employee(first, last, id) {
Employee.superclass.call(this, first, last);
this.id = id;
}
Class.extend(Employee, Person);
Employee.prototype.reverse = function() {
return Employee.superproto.reverse.call(this) + ': ' + this.id;
};
var peter = new Employee('Peter', 'Michaux', 3);
document.write(peter.reverse()); // Michaux, Peter: 3
delete Employee.prototype.reverse;
document.write(peter.reverse()); // Michaux, Peter
Comments
Have something to write? Comment on this article.