• SECOND Option: Multiple, Nested Module Files

    Create the following Something_Class.js and Something_methods.js files in the sandbox modules folder. As you notice, the class file uses the methods file and *'mixes' its properties - methods - into the prototype (added a sayGoodbye() as a second method to show how mixing in of multiple methods multiple is achieved).

    // Something_Class.js in .../modules folder of IDE Settings-PROJECT
    var Something = function(name) {
      this.name = name;
    };
    
    var methods = require("Something_methods");
    for (var methodName in methods) // mix separately defined methods into...
      Something.prototype[methodName] = methods[methodName]; // ...prototype
                          
    exports = Something;
    
    // Something_methods.js in .../modules folder of IDE Settings-PROJECT
    exports =
    { sayHello: function() {
        console.log("Hello, my name is " + this.name + "!");
      }
    , sayGoodbye: function() {
        console.log("Bye-bye from " + this.name + "!");
      }
    };
    

    Usage is only slightly different: Instead of pulling Something module, you pull Something_Class module, but you still pull only one module...:

    var Something = require("Something_Class"); // pull in class w/ require module
    var thisThing = new Something("ThisThing"); // create a 1st instance of class
    var thatThing = new Something("ThatThing"); // create a 2nd instance of class
    setWatch(function() { thisThing.sayHello(); // make 1st instance say hello...
      }, BTN1, { repeat:true, edge:"rising", debounce:50}); // ...on button press
    setWatch(function(){ thatThing.sayHello(); // make 2nd instance say hello...
      }, BTN1, { repeat:true, edge:"falling", debounce:50}); // ...on button release
    setTimeout(function(){ thisThing.sayGoodbye(); }, 45000);
    setTimeout(function(){ thatThing.sayGoodbye(); }, 60000);
    
    

    mixin - mixing the properties of one Javascript object into another one is a very Javascript typical pattern... that shows Javascripts extreme dynamic properties, and - neither last nor least - one that give Javascript almost the power of the Interfaces w/ Implementations pattern found in Java. (A class that implements multiple interfaces mixes multiple sets of methods into a new class definition, which can also be defined by a 'mixed in' constructor using a helper construct.)

About

Avatar for allObjects @allObjects started