Search code examples
javascriptobjectmoduleparentrequire

How to access parent variable on require module node


how i can access to parent variable on exports module?

function ThunderClient(key){//my class
    this.key = key //i want have access to this variable
}

ThunderClient.prototype.users = require('./modules/users')(route_rest,this.key); //this.key are key of ThunderClient

ThunderClient.prototype.address = require('./modules/address')(route_rest,this.key);//this.key are key of ThunderClient

require('./modules/address')(route_rest,this.key);

this.key is a key of ThunderClient (on construct i fill this variable). On my module users i want have access to this.key of ThunderClient but if i use "this.key" on require doesn't work, how i can this?


Solution

  • Have your imported functions at the top:

    var users = require('./modules/users');
    var address = require('./modules/address');
    

    Then just wrap those imported functions:

    ThunderClient.prototype.users = function(){ return users(route_rest, this.key); }
    ThunderClient.prototype.address = function(){ return address(route_rest, this.key); }
    

    If you want to have instance specific users assigned at creation then you'll need to add them to the created instance inside your constructor and not in the prototype.

    function ThunderClient(key){
        this.key = key;
        this.users = users(route_rest, this.key);
        this.address = address(route_rest, this.key);
    }