Organize prototype javascript while perserving object reference and inheritance

You could make Controls a class of it’s own:

var Controls = function (controllable_object) {
    this.ref = controllable_object;
};
Controls.prototype.next = function () {
    this.ref.foo();
}
// ..

var Carousel = function () {
    this.controls = new Controls(this);
};
// ..

This doesn’t allow you to override the implementation of Controls though. With more dependency injection you’d get something like:

var Controls = function (controllable_object) {
    this.ref = controllable_object;
};
Controls.prototype.next = function () {
    this.ref.foo();
}
// ..

var Carousel = function () {
        this.controllers = [];
    };
Carousel.prototype.addController = function (controller) {
        this.controllers.push(controller);
    };
// ..

var carousel = new Carousel();
carousel.addController(new Controls(carousel));

Leave a Comment