Node module.exports returns undefined

后端 未结 3 2048
滥情空心
滥情空心 2021-01-19 00:55

I am having an issue with Node.js and module.exports. I understand that module.exports is a call to return an object, that object having whatever p

相关标签:
3条回答
  • 2021-01-19 01:48

    I'd suggest wrapping the new call in it's own function then returning that:

    function Format(text) {
      this.text = text;
    }
    
    function formatting(text) {
      return new Format(text);
    }
    
    module.exports = formatting;
    

    This way you should still be able to do:

    var format = formatting('foo');
    console.log(format.text);
    


    Edit:

    In terms of the request stuff, one thing you have to remember is that in JavaScript, functions are still objects. This means you can still add properties and methods to them. This is what they're doing in request though overall it's a bit too complicated to explain every detail in this answer. From what I can tell, they add a bunch of methods (functions on an object) to the request function. This is why you can immediately call those methods like request(blah, blah).pipe(blah).on(blah) Based on what's returned from calling the request function, you can chain some of the other methods on the back of it. When you're using request it's not an object, it's a function (but still technically an object). To demonstrate how functions are still objects and how it's possible to add methods to them, check out this simple example code:

    function hey(){
      return;
    }
    
    hey.sayHello = function(name) {
      console.log('Hello ' + name);
    } 
    
    hey.sayHello('John'); //=> Hello John
    

    This is basically what they're doing, just a lot more complicated and with a lot more stuff going on.

    0 讨论(0)
  • 2021-01-19 01:48

    Try this:

    module formatting:

    function Format() {
        this.setter = function(text) {
          this.text = text;
        }
        this.show = function() {
          console.log(this.text);
        } 
    }
    //this says I want to return empty object of Format type created by Format constructor.
    
    module.exports = new Format();
    

    index.js

    var formatting = require('./formatting');
    formatting('Welcome');
    console.log(formatting.show());
    
    0 讨论(0)
  • 2021-01-19 02:01
    module.exports = Format;
    

    This will return the Format constructor when you will require('./formatting')

    On the other hand the code below will return an instance of Format, which you can directly call methods on:

    module.exports = new Format();
    
    0 讨论(0)
提交回复
热议问题