简体   繁体   中英

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!

this is what i do:

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

exports.myVar = 'foo';

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

You can try this:

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

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

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

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
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM