Some Notes About Modules

来源:互联网 发布:手机截图软件 编辑:程序博客网 时间:2024/04/19 12:25

These days theJian & me want to make some changes.
We decided to work together on a project which we call it the LASTWORD.
On SERVER side ,we decided to use Node.However ,when it comes to using thie amazing stuff,we got trapped in the “module” mechanism.
So I want to keep a note about the beautiful working way.The following information are extracted from online blogs.thanks to those who are working hard to make node better.

SAMPLE

modules can be reused in Node since they created.
In this way ,we can make our code more beautiful,and it is easy to create a module.
Every file can be a module ,so we create a test.js to explain it.

test.js

var name = “”;
function setName(n){
name = n;
}
function printName(){
console.log(name);
}
export.setName = setName;
export.printName = printName;
After that,you can require this test.js and use these two function.

By the way,export an object is also very easy.
another.js

var Student = function(){

var name = "";this.setName = function(n){    name = n;};this.printName = function(){      console.log(name);};

};

module.exports = Student;

module.exports and exports

In fact,module.exports is the ture port.Every module will create a MODULE object with an atrribute—modules whose initial value is an empty object.One module’s public port is this atrribute–module.exports.
For convenience,one module also provide an exports port which shares the same target with module.exports.It explains the strange phenomenon in which when module.exports point to an unempty object exports cannot work.Cause module.exports is assigned with different target from exports,it does nothing matter with export any more.

Require once

Another important thing need to pay attentation to is “require”.
Now matter how many times you require a module,all the reference get the only one instance.

0 0
原创粉丝点击