简体   繁体   中英

Accessing a function from a different function inside module.exports

I'm working on refactoring some code in JavaScript, a language I am not all too familiar with so I am having some issues understanding some of the bugs I'm facing.

The original code, which worked fine was in this format:

function doSomething(website){
//logic
}

function doSomethingElse(value){
   doSomething(value);
}

However, I had to put all the existing code inside a module export statement as I need to integrate it with other services. So now the code looks a little like:

module.exports = class DoAllThings{
  doSomething(website){
  //logic
  }

  doSomethingElse(value){
   doSomething(value);
  }
}

However this doesn't work as it says doSomething is not a function. I have tried setting the function to a var and accessing it that way, and accessing via .this as:

 this.doSomething(value); 

to no avail.

I have defined the module exports as a class so I can do this in another file:

 let accessVar = new DoAllThings(); 
 accessVar.doSomethingElse(value);

And there are other "classes" I will have to integrate following the pattern. So does anyone have any idea how I would go about accessing these functions? I figure it has something to do with the way I am returning things but I am not too sure.

One approach:

//I am kinda private, can't be accesed from outside
function doSomethingElse() {
  console.log('something else');
}
module.exports = {
  doSomething: function() {
    doSomethingElse();
  }
}

...

const yourModule = require('yourModule');
yourModule.doSomething() //console.log

Another:

const doSomethingElse = function() {
  console.log('something else')
}
const doSomething = function() {
  doSomethingElse();
}

module.exports = {doSomething}

//or
module.exports = {doSomething, doSomethingElse}

With a class:

module.exports = class Y {
  doSomething() {
    this.doSomethingElse();
  }

  doSomethingElse() {
    console.log('something else');
  }
}

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