Method binding

In JavaScript, an object’s methods are just functions. Functions are data. And that means I can do the following:

        var rex = new Dog('Rex');
        var speak = rex.speak;    // a method
        speak('biscuits');
            // -> "MY NAME IS AND I LIKE BISCUITS!"

Where did Rex’s name go? The thing is, we’ve called speak() outside the context of rex, so this inside the function no longer refers to the right thing. JS.Class gives each class instance a method() method, that returns a method by name, bound to its source object.

        var speak = rex.method('speak');
        speak('biscuits');
            // -> "MY NAME IS REX AND I LIKE BISCUITS!"

You can also do this with static methods:

        var User = new JS.Class({
          extend: {
            create: function(name) {
              return new this(name);
            }
          },
          initialize: function(name) {
            this.username = name;
          }
        });
        
        var u = User.method('create');
        u('James')    // -> {username: 'James'}