Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

javascript - What is the difference between require() and new require()?

The core of my question is, what's the difference between

var fs = new require('fs');

and

var fs = require('fs');

Are there any effects or caveats if I were to use new for all modules everywhere?

While using Webstorm, I noticed that I can get intellisense working only if I use new require('fs'). Before I start using it consistently for a better development experience, I wanted to know a bit more about it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all: Do not confuse new require("...") (which invokes require as a constructor) with new (require("...")) (which invokes the return value of the require call as a constructor). You are doing the first one.

require was not intended to be invoked as a constructor with new. That's not Node-idiomatic, and generally weird. You shouldn't do it, since it reduces the readbility of your code. A future reader might easily mistake it for new (require("...")) (i.e., calling new on a constructor that is being returned by require), since normal Node style does not use new with require.

Now, let's talk about actual side effects.

new causes a function to run its [[Construct]] internal method, which takes the following actions:

  • invoke the function with a this set to a newly-created object whose prototype is set to the function's prototype property

  • Return a result:

    • if the function returns an object, return the result of the function
    • if the function returns anything else, return the newly-created this object

The return value new require will be the same as require for all modules whose exports value is non-primitive (which is true of virtually any module; they typically export a plain object or a function, which is also a kind of object). In the rare case that your module does export a primitive, though, then new will deny you access to that value.

The only other possible difference between require(...) and new require(...) is that the new variant is supplied with a different this value. However, require appears to ignore its this value totally. (Note that Module.prototype.require -- a different function from normal require -- does use its this value, but that's only used when you require submodules from a module, using module.require(...).)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...