Is it possible to give javascript partial class behavior like C# or monkey patching like Ruby does?

前端 未结 5 1808
感动是毒
感动是毒 2021-01-01 05:14

The idea behind partial classes is that you can group certain functions together. The best example of this in C# is putting control definitions in one file and the event han

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 05:51

    I'm expanding upon Raynos' partial classes example. The following is tested and works:

    //  In Car.js
    function Car(domelement, wheels, engine, color) {
        this.domelem = domelement;
    
        //  Wire in partial classes from other files
        for(var i = 0, ii = Car.Partial.length; i < ii; i++) {
             Car.Partial[i].apply(this, arguments);
        }
    }
    Car.Partial = [];  //  Prepare for declaration of additional partial classes
    
    //  In Car.Events.js
    Car.Partial[0] = function Events() {
        //  Create some events on Car with jQuery
        $(this.domelem).click(function() { alert('Car clicked.'); });
    }
    

    You can then use a build tool to combine the files into a single script, or you can simply reference the files in order:

    
    
    
    

提交回复
热议问题