1. 程式人生 > >typeOf與 instanceof的區別

typeOf與 instanceof的區別

typeOf:      typeOf操作符是確定一個變數是字串,數值,布林值還是undefine或者是object的最佳工具。      var s=’tom’,str=‘22’;      var b = true,      var i = 22;      var u ;      var n = null;      var o = new Object();      var fun = function(){}      typeof s;//’string'      typeof str;//’string'      typeof b; //‘boolean'      typeof i;//’number'      typeof u;//'undefine'      typeof n;//'object'      typeof o;//‘object'       typeof fun;//‘function' instanceof:      instanceof操作符是確定一個物件是什麼型別的物件的工具。      alert(person instanceof Object);//變數person是Object 物件嗎?      alert(colors instanceof Array);//變數colors是Array 物件嗎?      alert(pattern instanceof RegExp);//變數pattern是RegExp 物件嗎? 所有引用型別的值都是Object的例項。 區別:typeof是判斷變數是什麼基本型別的;           instanceof是判斷物件到底是什麼型別的; constructor: function isArray(arr){ return typeof arr == "object" && arr.constructor == Array; } 很多情況下,我們可以使用instanceof運算子或物件的constructor屬性來檢測物件是否為陣列。例如很多JavaScript框架就是使用這兩種方法來判斷物件是否為陣列型別。 但是檢測在跨框架(cross-frame)頁面中的陣列時,會失敗。原因就是在不同框架(iframe)中建立的陣列不會相互共享其prototype屬性 <script> window.onload=function(){
var iframe_arr=new window.frames[0].Array; alert(iframe_arr instanceof Array); // false alert(iframe_arr.constructor == Array); // false } </script> 跨原型鏈呼叫toString()方法:Object.prototype.toString()。可以解決上面的跨框架問題。 當Object.prototype.toString(o)執行後,會執行以下步驟: 1)獲取物件o的class屬性。 2)連線字串:"[object "+結果(1)+"]" 3)返回 結果
Object.prototype.toString.call([]); // 返回 "[object Array]" Object.prototype.toString.call(/reg/ig); // 返回 "[object RegExp]"