JavaScript 中內置了兩個特殊的單體對象:Global 和 Math。它們不像普通對象那樣需要 new 來實例化,而是可以直接使用。下面分別剖析。
Global 是 JavaScript 中最特別的對象。所有不屬於其他對象的屬性和方法,最終都歸它所有。可以這樣理解:並不存在真正的全局變量或全局作用域,凡是在全局作用域中定義的屬性和函數,本質上都是 Global 對象的屬性。
1. URI 編碼方法
encodeURI() 主要用於編碼整個 URI,encodeURIComponent() 則用於編碼 URI 中的某一段。
var uri = "https://www.jb51 xxyh.com#login"; alert(encodeURI(uri)); // "https://www.jb51%20xxyh.com#login" alert(encodeURIComponent(uri)); // "http%3A%2F%2Fwww.jb51%20xxyh.com%23login"
encodeURI() 不會對本身屬於 URI 的特殊字符(冒號、正斜槓、問號、井號等)編碼,而 encodeURIComponent() 會把任何非標准字符都編碼。與之對應的解碼方法是 decodeURI 和 decodeURIComponent。
var uri = "http%3A%2F%2Fwww.jb51%20xxyh.com%23login"; alert(decodeURI(uri)); // "http%3A%2F%2Fwww.jb51 xxyh.com%23login" alert(decodeURIComponent(uri)); // https://www.jb51 xxyh.com#login
其中 decodeURI() 只能解碼由 encodeURI() 編碼的字符,decodeURIComponent() 則對應 decodeURIComponent()。
2. eval() 方法
eval() 只接受一個參數,即要執行的 JavaScript 字符串:
eval("alert('hello')"); 等同於 alert("hello");。
解析器調用 eval() 時,會把傳入參數當作真正的 JS 語句解析,並將執行結果插入原來位置。通過 eval() 執行的代碼被視為包含該調用的執行環境的一部分,因此擁有相同的作用域鏈,可以引用包含環境中定義的變量:
var msg = "good morning"; eval("alert(msg)"); // "good morning"
同樣可以在 eval() 中定義函數或變量,再在外部引用:
eval("function sayHi() {alert('hello')}");
eval("var msg = 'hello world'"); alert(msg); // "hello world"
需要注意,在 eval() 中創建的任何變量或函數都不會被提升,只有在 eval() 執行時才會創建。
3. window 對象
JavaScript 並未指明如何直接訪問 Global 對象,但浏覽器把它作為 window 對象的一部分來實現。因此,全局作用域中聲明的所有變量和函數,都是 window 對象的屬性:
var color = "red"; function sayColor() { alert(window.color); } window.sayColor();
取得 Global 對象的通用寫法:
var global = function () { return this; }();
Math 對象提供了豐富的數學計算能力。
1. 屬性
Math 的屬性多為數學中的特殊值,如圓周率、自然對數底等。

2. min() 與 max()
用於確定一組數值中的最小值和最大值,可接收任意多個參數:
var max = Math.max(4,89,65,34); alert(max); // 89 var min = Math.min(4,89,65,34); alert(min);
若數值存在數組中,可借助 apply() 傳入:
var values = [4,89,65,34]; var max = Math.max.apply(Math, values);
3. 捨入方法
• Math.ceil():向上捨入(進一法),小數位不為 0 就進位;
• Math.floor():向下捨入(取整法),捨去小數位;
• Math.round():標准捨入(四捨五入)。
alert(Math.ceil(11.4)); // 12 alert(Math.ceil(11.5)); // 12 alert(Math.ceil(11.8)); // 12 alert(Math.floor(11.4)); // 11 alert(Math.floor(11.5)); // 11 alert(Math.floor(11.8)); // 11 alert(Math.round(11.4)); // 11 alert(Math.round(11.5)); // 12 alert(Math.round(11.8)); // 12 alert(Math.ceil(-11.4)); // -11 alert(Math.ceil(-11.5)); // -11 alert(Math.ceil(-11.8)); // -11 alert(Math.floor(-11.4)); // -12 alert(Math.floor(-11.5)); // -12 alert(Math.floor(-11.8)); // -12 alert(Math.round(-11.4)); // -11 alert(Math.round(-11.5)); // -11 alert(Math.round(-11.8)); // -12
4. random() 方法
返回一個 0 ≤ r < 1 的隨機數。例如獲取 1 到 10 之間的整數:
var num = Math.floor(Math.random() * 10 + 1);
5. 其他方法
Math 還提供了大量完成各種簡單或複雜計算的方法。

ECMA-262 規定了這些方法,但不同實現的精度可能略有差異。掌握 Global 與 Math 這兩個單體對象,能讓日常開發事半功倍。