1. 程式人生 > >exports構建自定義模組(一)

exports構建自定義模組(一)

exports可以向外部檔案暴露方法和屬性,同過載單獨js檔案內寫方法向外部暴露呼叫方法就能完成模組的定義。

demo1:
exports_test1.js

var name;
exports.setName = function(newName){
    name = newName;
}

exports.sayHello = function(){
    console.log("hello:"+name);
}

方法的呼叫:

/*
 * require只會匯入一次模組
 *
 * */
var exportT = require('./exports_test1');
export
T.setName('zw'); var exportT = require('./exports_test1'); exportT.setName('zw2'); exportT.sayHello();

列印輸出:

hello:zw2

demo2:
exports_test2.js

function hello(){
    var name;
    this.setName = function(newName){
        name = newName;
    }
    this.sayHello = function(){
        console.log("hello:"
+name); } } module.exports = hello;

方法的呼叫:

var hello = require('./exports_test2');
var hello1 = new hello();
hello1.setName('zw');
hello1.sayHello();


var hello2 = new hello();
hello2.setName('z2');
hello2.sayHello();

列印輸出:

hello:zw
hello:z2