天天看點

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');
exportT.setName('zw');
var exportT = require('./exports_test1');
exportT.setName('zw2');
exportT.sayHello();
           

列印輸出:

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
           

繼續閱讀