JS中typeof與instanceof的區別

JavaScript 中typeofinstanceof 經常使用來判斷一個變量是否爲空,或者是什麼類型的。但它們之間仍是有區別的:數組

typeof

typeof 是一個一元運算,放在一個運算數以前,運算數能夠是任意類型。dom

它返回值是一個字符串,該字符串說明運算數的類型。(typeof 運算符返回一個用來表示表達式的數據類型的字符串。 )函數

typeof其實就是判斷參數是什麼類型的實例,就一個參數測試

typeof 通常只能返回以下幾個結果:"number"、"string"、"boolean"、"object"、"function" 和 "undefined"。prototype

運算數爲數字 typeof(x) = "number" code

字符串 typeof(x) = "string"對象

布爾值 typeof(x) = "boolean" 繼承

對象,數組和null typeof(x) = "object" ip

函數 typeof(x) = "function"原型鏈

console.log(typeof (123));//typeof(123)返回"number" 
console.log(typeof ("123"));//typeof("123")返回"string"
var param1 = "string";
var param2 = new Object();
var param3 = 10;
console.log(typeof(param1)+"\n"+typeof(param2)+"\n"+typeof(param3)); 
     // string object  number

咱們可使用 typeof 來獲取一個變量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 由於若是 a 不存在(未聲明)則會出錯,對於 Array,Null 等特殊對象使用 typeof 一概返回 object,這正是 typeof 的侷限性。

常常會在js裏用到數組,好比 多個名字相同的input, 如果動態生成的, 提交時就須要判斷其是不是數組.

  if(document.mylist.length != "undefined" ) {} //這個用法有誤.

正確的是 `if( typeof(document.mylist.length) != "undefined" ) {}` 

     或 `if( !isNaN(document.mylist.length) ) {}`

typeof的運算數未定義,返回的就是 "undefined".

在 JavaScript 中,判斷一個變量的類型嚐嚐會用 typeof 運算符,在使用 typeof 運算符時採用引用類型存儲值會出現一個問題,不管引用的是什麼類型的對象,它都返回 「object」。這就須要用到instanceof來檢測某個對象是否是另外一個對象的實例。

instanceof

instanceof 運算符用來測試一個對象在其原型鏈中是否存在一個構造函數的 prototype 屬性。

語法:object instanceof constructor
參數:object(要檢測的對象.)constructor(某個構造函數)
描述:instanceof 運算符用來檢測 constructor.prototype 是否存在於參數 object 的原型鏈上。

instance:實例,例子

a instanceof b?alert("true"):alert("false"); //a是b的實例?真:假

instanceof 用於判斷一個變量是否某個對象的實例,

如 :var a=new Array();

alert(a instanceof Array); // true,

同時 alert(a instanceof Object) //也會返回 true;

這是由於 Array 是 object 的子類。



再如:function test(){};

var a=new test();

alert(a instanceof test) 會返回true

alert(a==b);  //flase

案例:

另外,更重的一點是 `instanceof` 能夠在繼承關係中用來判斷一個實例是否屬於它的父類型。

例如:

function Foo(){} 
Foo.prototype = new Aoo();//JavaScript 原型繼承 
var foo = new Foo(); 
console.log(foo instanceof Foo)//true 
console.log(foo instanceof Aoo)//true

上面的代碼中是判斷了一層繼承關係中的父類,在多層繼承關係中,instanceof 運算符一樣適用。


又如:

console.log(Object instanceof Object);//true 
console.log(Function instanceof Function);//true 
console.log(Number instanceof Number);//false 
console.log(String instanceof String);//false  
console.log(Function instanceof Object);//true  
console.log(Foo instanceof Function);//true 
console.log(Foo instanceof Foo);//false
// 定義構造函數
function C(){} 
function D(){} 

var o = new C();

// true,由於 Object.getPrototypeOf(o) === C.prototype
o instanceof C; 

// false,由於 D.prototype不在o的原型鏈上
o instanceof D; 

o instanceof Object; // true,由於Object.prototype.isPrototypeOf(o)返回true
C.prototype instanceof Object // true,同上

C.prototype = {};
var o2 = new C();

o2 instanceof C; // true

o instanceof C; // false,C.prototype指向了一個空對象,這個空對象不在o的原型鏈上.

D.prototype = new C(); // 繼承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true

談到 instanceof 咱們要多插入一個問題,就是 functionarguments,咱們你們也許都認爲 arguments 是一個 Array,但若是使用 instaceof 去測試會發現 arguments 不是一個 Array 對象,儘管看起來很像。

另外:

測試 var a=new Array();if (a instanceof Object) alert('Y');else alert('N');

得'Y’

但 if (window instanceof Object) alert('Y');else alert('N');

得'N'

因此,這裏的 instanceof 測試的 object 是指 js 語法中的 object,不是指 dom 模型對象。

使用 typeof 會有些區別

alert(typeof(window)) 會得 object

須要注意的是,若是表達式 obj instanceof Foo 返回true,則並不意味着該表達式會永遠返回ture,由於Foo.prototype屬性的值有可能會改變,改變以後的值頗有可能不存在於obj的原型鏈上,這時原表達式的值就會成爲false。另一種狀況下,原表達式的值也會改變,就是改變對象obj的原型鏈的狀況,雖然在目前的ES規範中,咱們只能讀取對象的原型而不能改變它,但藉助於非標準的__proto__魔法屬性,是能夠實現的。好比執行obj.__proto__ = {}以後,obj instanceof Foo就會返回false了。

例子: 代表String對象和Date對象都屬於Object類型
下面的代碼使用了instanceof來證實:String和Date對象同時也屬於Object類型。

例子: 代表String對象和Date對象都屬於Object類型

下面的代碼使用了instanceof來證實:String和Date對象同時也屬於Object類型。
var simpleStr = "This is a simple string"; 
var myString  = new String();
var newStr    = new String("String created with constructor");
var myDate    = new Date();
var myObj     = {};

simpleStr instanceof String; // returns false, 檢查原型鏈會找到 undefined
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true

myObj instanceof Object;    // returns true, despite an undefined prototype
({})  instanceof Object;    // returns true, 同上

myString instanceof Date;   // returns false

myDate instanceof Date;     // returns true
myDate instanceof Object;   // returns true
myDate instanceof String;   // returns false
相關文章
相關標籤/搜索