How does require work with new operator in node.js?

后端 未结 1 1401
执念已碎
执念已碎 2020-12-01 18:29

Let\'s have a file.js with this code:

module.exports.func = function(txt) {
    this.a = 1;
    this.b = 2;
    console.log(txt, this);
    return this;
}


        
相关标签:
1条回答
  • 2020-12-01 19:16

    These two versions are fundamentally different.

    This one:

    new (require('./file')).func('r1');
    

    Executes the require, returning the exports of ./file and then calling the new operator on the results .

    This one:

    var r2 = new require('./file').func('r2');
    

    Invokes require as a constructor.


    Let's look at a more isolated and simple example:

    new Date() // creates a new date object
    new (Date()) // throws a TypeError: string is not a function
    
    0 讨论(0)
提交回复
热议问题