node. JS Learning Diary (ii) node. JS Scope

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.