0

I have the following situation. I'm trying to create an object that will be initialized then reused over the course of a script. Part of the construction of such an object requires a login to retrieve data from a webpage. This data will be kept within the object.

Consider a file called myThingAbove.js that contains this code:

module.exports = (function(){

     //need to keep these updated
     var a = {}, b = {};

     const myThing = function(options){
         somefun(args, function(err, resp){

                //stuff

                a = valueBasedOnResp;
                b = valueBasedOnRespAsWell;
         });
     })

     mything.prototype.myMethod = function(args) {
          // makes use of a and b
     }

return myThing;

})());

I'm initializing this "object" as follows:

const myThing = require('./myThingAbove.js');
const myObj = new myThing(args);

myObj.myMethod();

It looks like I'm not able to maintain a or b's state. The constructor call with the new statement sets these values as expected but they do not persist with myObj. How can I maintain the values of these variables within my instance of myObj?

I'm using NodeJS v8.5.0.

UPDATE: It's been pointed out that myObj.myMethod() and const myObj = new myThing(args); will be executed asynchronously. This may actually be my problem. Is there a way to guarantee myObj will be constructed before myObj.myMethod() is called?

joshin4colours
  • 1,656
  • 4
  • 16
  • 27
  • `this.a` is different from `a`. Maybe you want `a = valueBasedOnResp;` instead? Or should every instance have it's own copy of `a` and `b` (and if yes, what's the point of the `a` and `b` variables)? Can you provide a more complete example? Another problem: [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/218196) – Felix Kling Oct 20 '17 at 17:47
  • You don't need to use the revealing pattern in node. Every `module` is implicitly wrapped with its own revealing pattern, so save yourself the hassle of writing an IIFE, and just write it all in the top-level scope. – Patrick Roberts Oct 20 '17 at 17:49
  • @FelixKling good catch, I'll update the question as needed – joshin4colours Oct 20 '17 at 17:51
  • 3
    If `somefun` is asynchronous then you are executing `myMethod` **before** the callback passed to `somefun` is executed (i.e. before `a` and `b` are updated). What is the overall problem you are trying to solve? Why do you think you need a constructor function? Do you plan to create multiple instances? If so, why do all instances share `a` and `b`? There might be a much simpler solution to the problem you are actually trying to solve. – Felix Kling Oct 20 '17 at 17:53
  • your example code is invalid – Andrea Oct 20 '17 at 17:57

0 Answers0