Onga inc

subtitle

js_design_modukes

module パターン

導入しやすいパターンですね、global変数を増やす事なく、
単一の処理を追加する事ができます。
情報をカプセル化して、privateとpublicの変数・関数を作ることができます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var myModule = {

myProperty: "someValue",

// object literals can contain properties and methods.
// e.g we can define a further object for module configuration:
myConfig: {
useCaching: true,
language: "en"
},

// a very basic method
saySomething: function () {
console.log( "Where in the world is Paul Irish today?" );
},

// output a value based on the current configuration
reportMyConfig: function () {
console.log( "Caching is: " + ( this.myConfig.useCaching ? "enabled" : "disabled") );
},

// override the current configuration
updateMyConfig: function( newConfig ) {

if ( typeof newConfig === "object" ) {
this.myConfig = newConfig;
console.log( this.myConfig.language );
}
}
};

// Outputs: Where in the world is Paul Irish today?
myModule.saySomething();

// Outputs: Caching is: enabled
myModule.reportMyConfig();

// Outputs: fr
myModule.updateMyConfig({
language: "fr",
useCaching: false
});

// Outputs: Caching is: disabled
myModule.reportMyConfig();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var Sample = (function() {

// ここからprivateなエリア(外からアクセスはできない)
var _nickName = 'nickName';
var _age = 35;

function _init() {
// 何かしらの処理
}

function _sayHello() {
console.log('Hello,' + _nickName +'です');
}

function _sayHello2() {
console.log('Hello,' + _nickName +'です type2');
}

_init(); // 内部処理実行

return {
sayHello: _sayHello // 公開機能のみ返します。
sayHello2: _sayHello2 // 公開機能のみ返します。
}

})();

Sample._nickName = 'hogehogeくん' // 変更できない
Sample.sayHello(); // Hello, sampleくんです。

Onga

A designer, developer and entrepreneur. Spends his time travelling the world with a bag of kites. Likes journalism and publishing platforms.

Comments