achingbrain/bbq — Issue #1: Support for default class options
Author: alanshaw
Created: 2011-11-22 11:12:00+00:00
State: open

I've got a situation where it is desirable for a class to have a set of default options, so that the callee doesn't have to specify all options when creating an instance of the class.

I'm currently doing something like:

initialize: function($super, options) {
$super(options);
this.options = Object.extend({foo: 'bar'}, this.options);
}

I thought it would be nice if the root of the class hierarchy actually did this merge for me, if I defined a variable called "options" in my class. That way I save a bit of code and it also gives me a chance to explicitly state the class options (so that newcomers can easily see what options the class takes). The implementation would look something like:

var SuperClass = new Class.create({

initialize: function(options) {
this.options = Object.extend(this.options || {}, options);
}
});

var SubClass = new Class.create(SuperClass, {

options: {
val1: 'default',
val2: 'default'
},

initialize: function($super, options) {
$super(options);
}
});

var instance1 = new SubClass();

console.log('instance1.options.val1=' + instance1.options.val1);
console.log('instance1.options.val2=' + instance1.options.val2);

var instance2 = new SubClass({val2: 'foo'});

console.log('instance2.options.val1=' + instance1.options.val1);
console.log('instance2.options.val2=' + instance1.options.val2);

var instance3 = new SubClass({val1: 'foo', val2: 'foo'});

console.log('instance3.options.val1=' + instance1.options.val1);
console.log('instance3.options.val2=' + instance1.options.val2);