Movatterモバイル変換


[0]ホーム

URL:


Ruby's Module#remove_method and inheritance in JavaScript

Published July 24, 2006 inInheritance Pattern,JavaScript,Ruby

This article followsRuby's open classes and inheritance in JavaScript and shows that the simpleextend 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  endendclass Employee < Person  def initialize(first, last, id)    super(first, last)    @id = id  end  def reverse    super + ': ' + @id.to_s  endendpeter = Employee.new('Peter', 'Michaux', 3)puts peter.reverse # Michaux, Peter: 3class Employee  remove_method :reverseendputs 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: 3delete Employee.prototype.reverse;document.write(peter.reverse()); // Michaux, Peter

Comments

Have something to write?Comment on this article.

© 2006-2018 Peter Michaux

[8]ページ先頭

©2009-2025 Movatter.jp