JS中typeof與instanceof的區別

來源:互聯網
上載者:User

標籤:boolean   正是   http   window   文法   區別   head   script   nbsp   

JavaScript 中 typeof 和 instanceof 常用來判斷一個變數是否為空白,或者是什麼類型的。但它們之間還是有區別的:

typeof

typeof 是一個一元運算,放在一個運算數之前,運算數可以是任意類型。

它傳回值是一個字串,該字串說明運算數的類型。typeof 一般只能返回如下幾個結果:

number , boolean , string , function , object , undefined。

我們先看看各個資料類型對應typeof的值:

資料類型 Type
Undefined “undefined”
Null “object”
布爾值 “boolean”
數值 “number”
字串 “string”
Symbol (ECMAScript 6 新增) “symbol”
宿主對象(JS環境提供的,比如瀏覽器) Implementation-dependent
函數對象 “function”
任何其他對象 “object”

我們可以使用 typeof 來擷取一個變數是否存在,如 if(typeof a!="undefined"){ 因為如果 a 不存在(未聲明)則會出錯,對於 Array,Null 等特殊對象使用 typeof 一律返回 object,這正是 typeof 的局限性。

 

instanceof

instance 譯:執行個體,例子

instanceof運算子可以用來判斷某個建構函式的prototype屬性是否存在於另外一個要檢測對象的原型鏈上。 如果對原型不太瞭解,可以看看深入理解原型。

a instanceof b?; //a是b的執行個體?真:假

instanceof 用於判斷一個變數是否某個對象的執行個體,如 var a=new Array();; 會返回 true,同時 也會返回 true;這是因為 Array 是 object 的子類。再如:function test(){};var a=new test();alert(a instanceof test) 會返回

談到 instanceof 我們要多插入一個問題,就是 function 的 arguments,我們大家也許都認為 arguments 是一個 Array,但如果使用 instaceof 去測試會發現 arguments 不是一個 Array 對象,儘管看起來很像。

另外:

測試 var a=new Array();if (a instanceof Object) ;else ;

得‘Y’

但 if (window instanceof Object) ;

得‘N‘

所以,這裡的 instanceof 測試的 object 是指 js 文法中的 object,不是指 dom 模型對象。

使用 typeof 會有些區別

會得 object

JS中typeof與instanceof的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.