addMethods
1.6.0

addMethods(methods)

Adds methods to an existing class.

Class#addMethods is a method available on classes that have been defined with Class.create. It can be used to add new instance methods to that class, or overwrite existing methods, after the class has been defined.

New methods propagate down the inheritance chain. If the class has subclasses, those subclasses will receive the new methods — even in the context of $super calls. The new methods also propagate to instances of the class and of all its subclasses, even those that have already been instantiated.

Examples


var Animal = Class.create({
  initialize: function(name, sound) {
    this.name  = name;
    this.sound = sound;
  },

  speak: function() {
    alert(this.name + " says: " + this.sound + "!");
  }
});

// subclassing Animal
var Snake = Class.create(Animal, {
  initialize: function($super, name) {
    $super(name, 'hissssssssss');
  }
});

var ringneck = new Snake("Ringneck", "hissssssss");
ringneck.speak();

//-> alerts "Ringneck says: hissssssss!"

// adding Snake#speak (with a supercall)
Snake.addMethods({
  speak: function($super) {
    $super();
    alert("You should probably run. He looks really mad.");
  }
});

ringneck.speak();
//-> alerts "Ringneck says: hissssssss!"
//-> alerts "You should probably run. He looks really mad."

// redefining Animal#speak
Animal.addMethods({
  speak: function() {
    alert(this.name + 'snarls: ' + this.sound + '!');
  }
});

ringneck.speak();
//-> alerts "Ringneck snarls: hissssssss!"
//-> alerts "You should probably run. He looks really mad."