Organize prototype javascript while perserving object reference and inheritance

javascript, javascript-objects, oop

Solution

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));

Problem

I have built a large application using JavaScript prototype and inheritance. But I am having a hard time organizing my code. For example I have a class carousel which has many functions like this: ``` Carousel.prototype.next = function () {...} Carousel.prototype.prev = function () {..} Carousel.prototype.bindControls = function () {..} ``` I would like to organize my code like this : ``` Carousel.prototype.controls = { next: function () { ... } , prev: function() { ... }, bindControls: function () { .. } } ``` But this will cause the value of "this" being lost. I can keep track of it using a global instance but this will cause problems when the class is inherited for example In another file I have something like this to override parent class ``` BigCarousel.prototype.next = function () {...} ``` My inheritance is done like this: ``` Function.prototype.inheritsFrom = function (parentClass) { if (parentClass.constructor === Function) { //Normal Inheritance this.prototype = $.extend(this.prototype , new parentClass); this.prototype.constructor = this; this.prototype.parent = parentClass.prototype; } else { //Pure Virtual Inheritance this.prototype = $.extend(this.prototype, parentClass); this.prototype.constructor = this; this.prototype.parent = parentClass; } return this; }; ``` So I can do: ``` BigCarousel.inheritsFrom(Carousel) ``` Does anyone know how can I work around the "this" value ?

Original source

Related problems