《JavaScript進階程式設計 第三版》學習筆記 (十三)進階函數__區塊鏈
來源:互聯網
上載者:User
1.安全的原生類型檢驗 js的原生類型,可以用typeof判斷,但有時會失效。比如typeof array返回的不是Array,而是Object;再比如老版本IE,會將function識別為Object。另外一個判斷類型的是instanceof,它能夠在對象的原型鏈中尋找建構函式,但這種方法對於原生類型的判斷也會出問題,因為某些原生建構函式使用者是可以覆蓋的,比如Array和JSON。請看下面的例子:
[javascript] view plain copy function Array(){ this.type="new Array"; this.length=7; } var a=new Array(); alert(a.length);//7 alert(typeof a);//object alert(a instanceof Array);//true var b=[1,2,3]; alert(b.length);//3 alert(b[1]);//2 alert(typeof b);//object alert(b instanceof Array);//false 這是個很有意思的例子,我們覆蓋了Array的建構函式,然後建立了一個不是Array的對象a,但instanceof把它識別成了Array,相反,本來是Array的b,卻誤判成其他。
解決這一個問題的方法是利用toString。原生類型調用toString後會返回諸如"[object array]"的字串,即便建構函式被惡意覆蓋了,原生類型的toString方法是不會被覆蓋的。
[javascript] view plain copy function Array(){this.length=7;} var a=1; var b=true; var c="string"; var d=[]; var e=new Array(); console.log(Object.prototype.toString.call(a));//[object Number] console.log(Object.prototype.toString.call(b));//[object Boolean] console.log(Object.prototype.toString.call(c));//[object String] console.log(Object.prototype.toString.call(d));//[object Array] console.log(Object.prototype.toString.call(e));//[object Object] 注意:在老IE中以COM對象實現的函數,返回的是Object
2.範圍安全的建構函式 在說對象建立的時候,我們給出了很多構造對象的方法,後來在說繼承的時候,也使用了那些方法。但那些構造對象的方法都是不安全的。
[javascript] view plain copy function Person(name,age){ this.name=name; this.age=age; } var p1=new Person("Brain",18); var p2=Person("Brain",18); alert(p1.name);//Brain alert(p2);//undefined alert(window.name);//Brain 上面例子裡,有一個建構函式Person,p1是使用正確調用方式建立出來的對象,p2則使用了不正確的調用。這種不正確的調用有一個非常嚴重的副作用,就是在Person的執行空間中加入了name屬性和age屬性,當前的執行空間是window。解決這個問題的思路是讓建構函式new和不new的運行結果是一樣的,這在之前有一個解決方案,現在提出第二個解決方案。
[javascript] view plain copy function Person(name,age){ if(this instanceof Person){ this