Created
August 23, 2014 11:51
-
-
Save elrrrrrrr/dcced39258e48f3cd79c to your computer and use it in GitHub Desktop.
module.exports和exports的区别。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| Initially,module.exports=exports , and the require function returns the object module.exports refers to. | |
| if we add property to the object, say exports.a=1, then module.exports and exports still refer to the same object. So if we call require and assign the module to a variable, then the variable has a property a and it's value is 1; | |
| But if we override one of them, for example, exports=function(){}, then they are different now: exports refers to a new object and module.exports refer to the original object. And if we require the file, it will not return the new object, since module.exports is not refer to the new object. | |
| For me, i will keep adding new property, or override both of them to a new object. Just override one is not right. And keep in mind that module.exports is the real boss. | |
| **/ | |
| var module.exports = {}; | |
| var exports = module.exports; | |
| exports = function(){}; // this will not work! as it make the exports to some other pointer | |
| module.exports = function(){}; // it works! cause finally nodejs make the module.exports to export. | |
| exports.abc = function(){}; // works! | |
| exports.efg = function(){}; // works! | |
| module.exports = function(){}; // from now on we have to using module.exports to attach more stuff to exports. | |
| module.exports.a = 'value a'; // works | |
| exports.b = 'value b'; // the b will nerver be seen cause of the first line of code we have do it before (or later) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment