Extend on Class

Add a backbone-like extend method onto your CoffeeScript classes, making it easy for JavaScript users to extend your CoffeeScript classes

by Benjamin Lupton

HTML

<script src="http://wzrd.in/bundle/csextends"></script>
<h1><a href="https://github.com/bevry/csextends">Coffee-Script Extends</a></h1>

Use the Coffee-Script extends keyword outside of Coffee-Script. Useful for easily extending existing existing classes, e.g. <code>require('csextends')(klass, extensions)</code>, and for providing your module consumers with an easy way to extend your classes, i.e. <code>Backbone.Model.extend(extensions)</code>.

<p>Click "Run" in the blue bar above, and open your console for a demo.</p>

JavaScript

// Create a Class
var Person = function(name){
    if ( name )  this.name = name
}
Person.prototype.name = 'Unknown'
Person.prototype.hello = function(){
    console.log('Hello '+this.name+'!')
}

// Extend the class
var Child = require('csextends')(Person, {
    constructor: function(name, mother, father){
        Person.call(this, name)
        this.mother = mother
        this.father = father
    },
    mother: null,
    father: null,
    heyYaAll: function(){
        this.hello()
        this.mother.hello()
        this.father.hello()
    }
})

// Create some people
var eve = new Person('Eve')
var adam = new Person('Adam')
var me = new Child(null, eve, adam)
me.heyYaAll()
// Hello Unknown!
// Hello Eve!
// Hello Adam!

// Is me still a person
console.log(me instanceof Person)  // true


// Now let's make this easier for people in the future
Person.subclass = require('csextends')
// Now, instead of doing:
//   var Child = require('csextends')(Person, extensions)
// We can now do:
//   var Child = Person.subclass(extensions)
// Which is very useful for module consumers.

// If you use CoffeeScript, you can accomplish the above by doing:
//   class Person
//     @subclass: require('csextends')
// Then your javascript consumers can do:
//   var Child = Person.subclass(extensions)
// Just as before, which is really good for JavaScript users.