You are reading a single comment by @dwallersv and its replies. Click here to read the full conversation.
  • I normally think of myself as a pretty bright person, but for the life of me I seem to be dumb as a lump of granite when it comes to the Module mechanism. What I want to do is conceptually pretty simple: Make a reusable object class. Maybe the module mechanism isn't suited for this? After half an hour looking through source code for a dozen modules or so, I couldn't find anything that looked like what I'm trying to do.

    I'd like to be able to do the following... The application would be coded as follows:

    require("myClass");
    
    abc = new myClass();
    console.log(abc.add(1,2));
    console.log(abc.getNextPresident());
    

    And the module, myClass.js, looks like this:

    function myClass() {
        this.nextPresident = "Bozo the clown";
    }
    
    myClass.prototype.add = function(a,b) { return a+b; };
    myClass.prototype.getNextPresident = function() { return this.nextPresident; };
    
    exports myClass;
    

    This, doesn't work. After the require, Espruino seems completely unaware of any constructor function "myClass".

    I can see how to work around this by adding an exported interface to create an object instance directly (this is done again and again in modules with the common 'connect' function on an exports declaration), but this is very "kludgy" to me -- isn't there any way to simply include something that acts like a traditional library?

    Also, I find that when I do this, it results in a doubling of space usage. The module containing all the method functions gets cached (one copy of everything), then all these functions get created again when constructed in the initial call. To make it clearer, here's what I've done to make this work:

    exports myClass.init = function() {
    	myClass = function() {
    	    this.nextPresident = "Bozo the clown";
    	};
    	
    	myClass.prototype.add = function(a,b) { return a+b; };
    	myClass.prototype.getNextPresident = function() { return this.nextPresident; };
    };
    

    Then, I use the module like this and it works:

    require("myClass").init();
    
    abc = new myClass();
    console.log(abc.add(1,2));
    console.log(abc.getNextPresident());
    

    Problem #1 is it uses 2x the space. I think this is because the call above caches the modules code as part of the 'require' call, and then the init() loads another copy of the class (constructor and prototype functions) again in memory. #2: I don't like it. Awkward.

    #1 is the real problem. I can live with #2.

    Is there some way to expose the function created when the module is loaded and executed in the root scope, as described in the modules page? This would address both #1 and #2.

About

Avatar for dwallersv @dwallersv started