Skip to content
uupaa edited this page May 19, 2017 · 36 revisions

このエントリでは、WebModule に使われている Idiom(トリック) について解説しています。


WebModule はどこでも動きます。

この「どこでも動く」JavaScriptを実現するためのイディオムが WebModuleIdiom です。 この idiom を使うと、各プラットフォームにおけるルートオブジェクト(GLOBAL object)を獲得する事ができます。

// WebModuleIdiom
// var GLOBAL = (this || 0).self || global; // version 0.7.3

var GLOBAL = (this || 0).self || (typeof self !== "undefined") ? self : global; // support ESModules

GLOBAL が既に宣言されている環境では global の値で GLOBAL を上書きします、electron や Node.js がこのケースです。
GLOBAL が undefined の場合は WebModuleIdiom を各プラットフォームの都合に合わせて評価し、Global Object を獲得します。

platform this self global expression and result
Browser (window ││ 0).self ││ (true) ? self : undefined
(window).self
window.self
→ Window Object
ESModules (undefined ││ 0).self ││ (true) ? self : undefined
(0).self ││ self
undefined ││ self
→ Window Object
Worker (WorkerGlobalScope ││ 0).self ││ (true) ? self : undefined
(WorkerGlobalScope).self
WorkerGlobalScope.self
→ WorkerGlobalScope Object
Node.js (global ││ 0).self ││ (false) ? undefined : global
(GLOBAL).self ││ global
undefined ││ global
global
→ Global Object
Electron
main
context
(global ││ 0).self ││ (true) ? self : global
(GLOBAL).self ││ self
undefined ││ self
global
→ Global Object
Electron
render
context
(window ││ 0).self ││ (true) ? self : undefined
(window).self
window.self
→ Window Object
NW.js
node
context
(global ││ 0).self ││ (true) ? self : global
(GLOBAL).self ││ self
undefined ││ self
global
→ Global Object
NW.js
browser
context
(window ││ 0).self ││ (true) ? self : undefined
(window).self
window.self
→ Window Object