Chapter 6, Inheritance

Lets solve the following exercise:

Exercises

  1. Multiple inheritance by mixing into the prototype, for example:
            var my = objectMulti(obj, another_obj, a_third, { 
              additional: "properties" 
            }); 
            A possible solution: 
            function objectMulti() { 
              var Constr, i, prop, mixme; 
     
            // constructor that sets own properties 
            var Constr = function (props) { 
              for (var prop in props) { 
                this[prop] = props[prop]; 
              } 
            }; 
     
           // mix into the prototype 
           for (var i = 0; i < arguments.length - 1; i++) { 
             var mixme = arguments[i]; 
             for (var prop in mixme) { 
               Constr.prototype[prop] = mixme[prop]; 
             } 
           } 
     
          return new Constr(arguments[arguments.length - 1]);
       } 
    

    Testing:

     > var obj_a = {a: 1}; > var obj_b = {a: 2, b: 2}; > var obj_c = {c: 3}; > var my = objectMulti(obj_a, obj_b, ...

Get Object-Oriented JavaScript - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.