Organize prototype javascript while perserving object reference and inheritance

前端 未结 3 2103
小蘑菇
小蘑菇 2020-11-22 05:50

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 ma

3条回答
  •  长发绾君心
    2020-11-22 06:21

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

提交回复
热议问题