I have a Mootools class:
var Foo = new Class({
initialize: function(param1, param2) {
// do stuff
}
});
The values to initialize Foo with are in an array:
a = ['value1', 'value2'];
How can I use the values from a
to initialize an instance of Foo
?
I'd go with extending the proto of the class so it does not care (see Felix' answer).
var Foo = new Class({
initialize: function(param1, param2) {
console.log(param1, param2);
}
});
(function(){
var oldFoo = Foo.prototype.initialize;
Foo.implement({
initialize: function(){
var args = typeOf(arguments[0]) == 'array' ? arguments[0] : arguments;
return oldFoo.apply(this, args);
}
});
}());
new Foo(['one', 'two']); // one two
new Foo('three', 'four'); // three four
It involves less hacking and is probably easier to understand/maintain than creating special constructor abstractions.
if you can, you can even do
var Foo2 = new Class({
Extends: Foo,
initialize: function () {
var args = typeOf(arguments[0]) == 'array' ? arguments[0] : arguments;
this.parent.apply(this, args);
}
});
new Foo2(['one', 'two']);
new Foo2('three', 'four');
Thus, making a very clear abstraction without modifying the parent proto and expectation - and keeping pesky SOLID principles assholes happy :D