How to use mixins properly in Javascript

前端 未结 4 1171
花落未央
花落未央 2020-11-28 15:13

I am organizing a small enterprise application but would like to be as DRY as possible. As a result, I\'ve been looking at mixin libraries.

I came across this librar

4条回答
  •  清酒与你
    2020-11-28 15:35

    A mixin is just a different conceptual idea, of how to organize code and inheritance. You can of course combine it with using classical or prototypal inheritance, but it also works stand-alone, so to speak.

    For instance, instead of creating "delegated" object properties/lookups (like prototypal inheritance), we would truly "form" new stand-alone objects, from multiple other objects. This is also called "multiple inheritance" sometimes and that cannot get achieved easily with Javascripts prototypal inheritance alone.

    As an example:

    var pianist = {
       play: function() {}
    };
    
    var programmner: {
       code: function() {}
    };
    

    And now we could create another Object, like

    var Jim = Object.create( null ); // create a fully self-defining object
    
    extend( Jim, pianist );
    extend( Jim, programmer );
    

    and this pseudo extend method could look like (ES5):

    function extend( target, source ) {
        Object.getOwnPropertyNames( source ).forEach(function( key ) {
            Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key)) });
    
        return target
    }
    

    I actually didn't answer your questions properly, but I felt like there is no real answer to your question. It is as real as you are going to use it, there is no "application specific" use case really.

提交回复
热议问题