Traits / Mix-ins

A trait or mix-in defines a reusable portion of a class body and can be used in any class definition to prevent horizontal code duplication. A trait is created using a regular JavaScript object and injected into a class definition with the uses parameter.

Example #1: Applying a trait

// Define a trait for the 'name' property.
var NameTrait = {
    'public string name' : 'Bob'
};

// Create an empty class that uses the NameTrait.
var MyClass = Class({ uses: NameTrait }, {
    // ...
});

var mc = new MyClass();

// Print "Bob" to the console
console.log(mc.getName());

Example #2: Applying multiple traits

// Create another trait for the age property and add a method to it.
var AgeTrait = {
    'public number age' : 42,

    'public isOlderThan(number)' : function(age) {
        return this.age > age;
    }
};

// Create an empty class that uses the NameTrait and AgeTrait.
var MyClass = Class({ uses: [NameTrait, AgeTrait] }, {
    // ...
});

var bob = new MyClass();
// Print "Bob" and his age to the console if his age exteeds 40.
if (bob.isOlderThan(40)) {
    console.log(bob.getName(), 'age:', bob.getAge());
}