-
Notifications
You must be signed in to change notification settings - Fork 8
WebModuleIdiom
uupaa edited this page May 25, 2015
·
36 revisions
このページは旧バージョンの内容に基づいています。近日中にリライトを行います。2015-05-26 uupaa
WebModule idiom は、どこでも動くJavaScriptコードを記述するためのイディオム(トリックの一種)です。
WebModule idiom を使うと、各プラットフォームにおけるルートオブジェクト(global object)を獲得する事ができます。
2014〜2015年は version 2 のスタイルが使われています。
// WebModule idiom version 2
(function(global) {
"use strict";
// global["MyModule"].say("hello");
})((this || 0).self || global);WebModule idiom version 2 は各プラットフォームにおいて以下のように評価されます。
| platform | expression and result |
|---|---|
| old Node.js |
((undefined ││ 0).self ││ global)→ ((0).self ││ global)→ ((undefined ││ global)→ (global)→ Global Object |
| new Node.js NW.js (Node context) |
((global ││ 0).self ││ global)→ ((global).self ││ global)→ ((undefined ││ global)→ (global)→ Global Object |
| WebWorkers |
((WorkerGlobalScope ││ 0).self ││ undefined)→ ((WorkerGlobalScope).self)→ (WorkerGlobalScope.self)→ Global Object |
| Browser NW.js (Browser context) |
((window ││ 0).self ││ undefined)→ ((window).self)→ (window.self)→ Global Object |
以下は、2013年に使用されていた古い書き方(version 1)です。
// WebModule idiom version 1
(function(global) {
"use strict";
// global["MyModule"].say("hello");
})(this.self || global);ES6 Module スコープ内はデフォルトで strict モードになります。
また strict モードにおいて this は undefined になるため、WebModule idiom version 2 の ((this ││ 0).self ││ global) がエラーになる環境も存在します。
(function(global) {
"use strict";
})((this || 0).self || global); // -> Error "global" is not defined.そのような場合は var global = global || self; を使うと問題を解決可能な場合があります。
var global = global || self;
(function(global) {
"use strict";
})(global);