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

前端 未结 5 1789
感动是毒
感动是毒 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 06:12

    // file 1
    
    function augment() {
        this.monkey = "monkey";
    }
    
    // file 2
    
    function augmentMore() {
        this.patch = "patch";
    }
    
    // file 3
    
    var o = {};
    augment.call(o);
    augmentMore.call(o);
    console.log(o.monkey + o.patch);
    

    Monkey patching works. partial classes can work by convention. For example consider this convention.

    // file main
    function SomeObject() {
        for (var i = 0, ii = SomeObject.Partial.length; i < ii; i++) {
             SomeObject.Partial[i].apply(this, arguments);
        }
    }
    
    SomeObject.Partial.SomeName = function() {
       ...
    }
    
    // file extra
    SomeObject.Partial.SomeOtherName = function() {
       ...
    }
    

    JavaScript is surprisingly powerful. Was there a specific example you were looking for?

提交回复
热议问题