2014-10-10 00:00

[API-d13] - [Javascript 番外篇] Javascript require/ module/ Module Pattern

接下來幾天會探討 node.js 的特性,由於比較少在寫 js ,因此有錯請指正

在 node.js 裏,要讀取外部模組都是透過 require 和 exports 來做溝通

以下列出這次最簡單 module 的例子

//hello.js
console.log('Hello World');
// app.js
require('./hello.js');

##Module 也是有 Pattern 的

第一種: Global (Not so good)

// foo.js
foo = function() {
	console.log("foo!");
}

// app.js
require('./foo.js');
foo();

第二種: export an anonymous function

// foo.js
module.exports = function() {
	console.log("foo! YA");
};

// app.js
var test = require("./foo.js");
test();

第三種: export a named function

// bar.js
exports.bar = function() {
	console.log("bar");
}

// app.js
var bar = require('./bar.js').bar;
bar();

第四種: exports an anoymous object

// bar4.js
var Bar4 = function() {};

Bar4.prototype.say = function() {
    console.log('bar4');
};

module.exports = new Bar4();

// app.js 
var b = require('./bar4.js');
b.say();

第五種: export a named object

// bar5.js
var Bar5 = function() {};

Bar5.prototype.say = function() {
    console.log("bar5");
};

exports.Bar5 = new Bar5();

// app.js
var b = require('./bar5.js').Bar5;
b.say();

第六種: export an anonymous prototype

// cool.js
var Cool = function() {};

Cool.prototype.say = function() {
    console.log('Cool!');
};

module.exports = Cool;

// app.js
var Cool = require('./cool.js');
var coo = new Cool();
coo.say();

第七種: export a named prototype

// ang.js
var Ang = function () {};

Ang.prototype.say = function () {
    console.log('Ang!');
};

exports.Ang = Ang;

// app.js
var Ang = require('./ang.js').Ang;
var wer = new Ang();
wer.say();

##exports v.s. module.exports

exports 是 module.exports 的輔助方法

以下有個例子會執行錯誤:

// ya.js
module.exports = "YA";
exports.name = function() {
    console.log('My name is kerkerj');
};

// app.js
var ya = require('./ya.js');
ya.name(); TypeError: Cannot call method 'name' of undefined

在 ya.js 中 module.exports 有屬性了

因此下面的 export.name 就沒有被加入了

如果 module.exports 沒有任何屬性被加入的話,

exports 若有屬性了,則會交給 module.exports

反之就是剛剛的情況,moduel.exports 已經有屬性了,因此 export.name 就沒有作用了

延伸閱讀

##Module as class

直接看例子吧 XD

// user.js
module.exports = function(name, age) {
    this.name = name;
    this.age = age;
    this.about = function() {
        console.log(this.name +' is '+ this.age +' years old');
    };
};

// app.js
var User = require('./user.js');
var kerkerj = new User('kerkerj', 18);
kerkerj.about(); 

Share

comments powered by Disqus