1. 在你的一个模块文件module.js中 写入:
<pre class="prettyprint prettyprinted" style="border-width: 1px 1px 1px 4px; border-style: solid; border-color: rgb(221, 221, 221); margin: 15px auto; padding: 10px 15px; font-stretch: normal; line-height: 20px; font-family: 'courier new'; white-space: pre-wrap; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: url("/images/codecolorer_bg.gif") 50% 0% rgb(251, 251, 251);"><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);">exports</span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">.</span><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);">world </span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">=</span><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);"> </span><span class="kwd" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 136);">function</span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">()</span><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);"> </span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">{</span><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);">
console</span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">.</span><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);">log</span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">(</span><span class="str" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 136, 0);">'this is public interface'</span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">);</span><span class="pln" style="border: 0px; margin: 0px; padding: 0px; color: rgb(0, 0, 0);">
</span><span class="pun" style="border: 0px; margin: 0px; padding: 0px; color: rgb(102, 102, 0);">}</span>
2. 然后在你的main.js 文件中调用这个模块
<pre class="prettyprint prettyprinted" style="margin: 15px auto; border-width: 1px 1px 1px 4px; border-style: solid; border-color: rgb(221, 221, 221); padding: 10px 15px; font-stretch: normal; line-height: 20px; font-family: 'courier new'; white-space: pre-wrap; word-break: break-all; word-wrap: break-word; background: url("/images/codecolorer_bg.gif") 50% 0% rgb(251, 251, 251);">require("./module"); /*表示调用当前文件夹下的module文件*/
如果只是想封装一个对象作为公共接口。
//test.js function Hello() { var name; this.setName = function(thyName) { name = thyName; }; this.sayHello = function() { console.log('Hello ' + name); }; }; module.exports = Hello;然后main.js 便可以访问了
//main.js var Hello = require('./hello'); hello = new Hello(); hello.setName('BYVoid'); hello.sayHello();