Tag: module scope chain Diary error col var exports load default
node. JS Scope
Test whether the package1 can invoke functions within Package2 through require ("./package2"):
1 // Paackage1.js 2 var a1 = 1 3 4 require ("./package2" ); 5 6 /* Even if require Package2, you cannot call function double_a */ 7 a1 = double_a (A1); // double_a is not defined 8 9 console.log ("package1:" + A1);
1 // Paackage2.js 2 function Double_a (a) {3 return A * 2; 4 }56 exports.double_a = double_a;
Error, and cannot call
Package1 the correct way to invoke a function within Package2:
1 // Package1 2 var a1 = 1; 3 4 /* todo: Gets the exports object for Package2 */ Span style= "COLOR: #008080" >5 var Package2 = require ("./package2" 6 7 A1 = Package2.double_a (A1); 8 console.log ("Package2:" + A1);
1 // Package2 2 function Double_a (a) {3 return A * 2; 4 }56/*TODO: Mount the double_a to the Exports object */7 exports.double_a = double_a;
function successfully called
Try another one, use the scope chain, let Package1 get the variable inside the Package2
1 // Package1 2 var Package2 = require (". /package2 " 3 console.log ("Name:" + package2.getname ());
1 // Package2 2 var name = "Lyjn"; 3 4 /* Todo:exports Set a GetName method to get the name */ 5 function () {6 return name; 7 };
Fully OK
2. Knowledge points in node only module scope, no global scope require the main role
1.加载模块并执行模块中的代码;2.返回exports对象;
Exports object
1.所有模块都有一个exports对象,默认值是一个空对象`{}`;2.可以给exports对象添加属性;
Little Tricks
1.require js file can be shed. Js,require ("./package.js") is equivalent to require ("./package")
node. JS Learning Diary (ii) node. JS Scope