McLovin
McLovin

Reputation: 1601

Node js using "this" from function call within module.exports

I am calling a local function from within a module.exports function. How can I access the exports this object?

exports.myVar = 'foo'

exports.myFunc = function() {
  localFunc()
}

function localFunc() {
  console.log(this.myVar) //Undefined
}

I have tried using localFunc().bind(this) but this does not work either. Any help is appreciated!

Upvotes: 0

Views: 2356

Answers (5)

leisheng
leisheng

Reputation: 382

localFunc.bind(this) just returns a new function which is the localFunc function, but with this bound to whatever you put in the parentheses. You need to actually assign the new function (returned by localFunc.bind) back to localFunc. Here are two simple examples:

exports.myVar = 'foo';

exports.myFunc = function() {
    localFunc = localFunc.bind(this);
    localFunc();
};

function localFunc() {
    console.log(this.myVar);
}

or:

exports.myVar = 'foo';

exports.myFunc = function() {
    localFunc();
};

function localFunc() {
    console.log(this.myVar);
}
localFunc = localFunc.bind(exports);

The 2nd option is probably better than the first because in the first example, you have to rebind the function every time exports.myFunc is called.

Upvotes: 0

Papandadj
Papandadj

Reputation: 94

two ways can resolve you issue.

the first:

exports.myVar = 'foo'

exports.myFunc = function() {
  that = this;
  localFunc(that)
}
function localFunc(that) {
  console.log(that.myVar) //foo
}

the second

exports.myVar = 'foo'

exports.myFunc = function() {
  localFunc()
}

localFunc = ()=> {
  console.log(this.myVar) //foo
}

Upvotes: 1

Ahmed Subkhi
Ahmed Subkhi

Reputation: 49

You can try this:

var data = module.exports = {
  myVar: 'foo',

  myFunc: function() {
    localFunc();
  }
}

function localFunc() {
  console.log(data.myVar);
}

Upvotes: 1

MudOnTire
MudOnTire

Reputation: 506

this is what i do:

function localFunc() {
   const self = exports;
   console.log(self.myVar);
}

exports.myVar = 'foo';

exports.myFunc = function () {
    localFunc();
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190905

Just use exports. Or declare myVar to be a variable, assign it to the exports and create a closure around it for localFunc.

this only really makes sense when you are event binding and/or creating objects.

Upvotes: 0

Related Questions