Organize prototype javascript while perserving object reference and inheritance

前端 未结 3 2092
小蘑菇
小蘑菇 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:23

    You can use the .bind method of Function.

    In Javascript Functions inherit from Object, so they have their own methods. One of those methods is .bind:

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

    Also you are doing inheritance wrong, the right way with raw Javascript is:

    ChildClass= function() {
        ParentClass.apply(this, arguments); //calling parent constructor
        //constructor
    };
    
    ChildClass.prototype= new ParentClass();
    

    Then you can simply do this on your constructor:

    Courossel= function() {
        ParentClass.apply(this, arguments); //calling parent constructor
        this.controls.next.bind(this);
        this.controls.prev.bind(this);
        this.controls.bindControls.bind(this);
    }
    

    But I have to say that Frits suggestion is better, make the controls their own class and instantiate it on Carousel constructor passing a reference to your Carousel instance (the this keyword). Just don't call it ".ref", it's confusing.

提交回复
热议问题