javascript那些事兒(二)Global對象用法,javascriptglobal
1、Global對象: 所有在全域範圍內定義的屬性和方法,都是Global對象的屬性
2、Global對象不直接使用,並且不能用new 運算子建立,它在 Scripting 引擎被初始化時建立,並立即使其方法和屬性可用。
例如:isNaN,isFinite(),parseInt(),parseFloat()都是Global對象的方法
下面介紹一下比較重要的幾個方法
(1)URI編碼解碼:encodeURI()\encodeURIComponent(), decodeURI\decodeURIComponent()
encodeURI()和encodeURIComponent()用於對URI(通用資源標識符)進行編碼,以便發送給瀏覽器。
瀏覽器不能理解和接收一些特殊字元,比如:空格,所以這兩個方法用UTF-8編碼替換URI中的無效字元以使瀏覽器能夠識別。
encodeURI(): 主要用於整個URI,不會對本身屬於URI的特殊字元進行編碼,如冒號,正斜杠、問號、井號
encodeURIComponent() : 主要用於對URI中某一段進行編碼,會對它發現的任何非標準字元進行編碼。
var uri = "http://www.baidu.com/aa value#query";//只有空格被替換console.log(encodeURI(uri)); //輸出:http://www.baidu.com/aa%20value#query,把空格編碼成%20//使用對應的編碼替換所有非字母字元console.log(encodeURIComponent(uri)); //輸出: http%3A%2F%2Fwww.baidu.com%2Faa%20value%23query//最佳實務://encodeURI: 對整個URI使用//encodeURIComponent(): 對URI後面的字串使用////decodeURI() : 對使用encodeURI編碼的字元進行解碼//decodeURIComponent() : 對使用encodeURIComponent編碼的字元進行解碼var uri2 = "http://www.baidu.com/aa%20value#query";console.log(decodeURI(uri2)); //http://www.baidu.com/aa value#queryvar uri3 = "http%3A%2F%2Fwww.baidu.com%2Faa%20value%23query";console.log(decodeURI(uri3)); //http%3A%2F%2Fwww.baidu.com%2Faa value%23queryconsole.log(decodeURIComponent(uri3)); //http://www.baidu.com/aa value#query
(2)eval() : 接收一個參數,即javascript字串,類似於一個ECMAScript解析器:
eval("alert('hello,nodejs')"); //等價於 alert('hello,nodejs');//在eval()中執行的代碼被認為是包含該次調用的執行環境的一部分,被執行的代碼與eval語句執行環境具有相同的範圍鏈var str = "hello,nodejs";eval("alert(str)"); // alert("hello,nodejs");eval("function hello(){alert('hello,world');}");hello(); //hello,world//strict 模式下,在外部存取不到eval()中定義的任何變數或函數,同樣,在strict 模式下,為eval也會導致錯誤產生。"user strict";eval("var str = 'hello,nodejs';"); alert(str); //錯誤
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">(3)Global對象屬性:undefined,NaN,Infinity,都是Global對象的屬性。</span>
此外,所有原生類型的建構函式也都是Global對象的屬性:Object,Function,Array,Number,Boolean,String.
(4)window對象:在全域範圍中聲明的所有變數和函數,都是window對象的屬性:
var name = "xiaoming"; function printName(){ alert(window.name); } window.printName(); //'xiaoming'