寫javascirpt程式碼時,typeof和instanceof這兩個運算子時不時就會用到,堪稱必用。但是!使用它們總是不能直接的得到想要的結果,非常糾結,普遍的說法認為“這兩個操作符或許是javascript中最大的設計缺陷,因為幾乎不可能從他們那裡得到想要的結果”
typeof
說明:typeof回傳一個表達式的資料類型的字串,傳回結果為js基本的資料類型,包括number,boolean,string,object,undefined,function。
從說明來看,看起來沒什麼問題。
下面的程式碼寫了一個數值變量,typeof後的結果是"number"。
var a = 1; typeof(a)); //=>number
如果用Number型別的建構子new一個變數的話,typeof後的結果是"object"。
var a = new Number(1);
console.log(typeof(a)); //=>object
上面的這兩個輸出結果看似沒啥問題,這一點從書上看來是理所當然的事情,因為javascript就是這樣設計的。
但是!問題就在於既然呼叫了typeof就應該要準確地傳回一個變數的類型,不管是直接用值創建的還是用類型的構造函數創建的,否則!我還用你做啥!
那麼對於:
var a = 1; 🎜>var b = new Number(1);
a和b變數的型別準確的說來都應該是Number才是想要的結果。
而準確的類型資訊保存在變數的內部屬性 [[Class]] 的值中,透過使用定義在 Object.prototype 上的方法 toString來取得。
取得類型資訊:
var a = 1;
var b = new Number(1);
console.log(Object.prototype.toString.call(a));
console.log(Object.prototype.toString.call(b ));
輸出:
程式碼如下:
程式碼如下:
複製程式碼
程式碼如下:
var a = 1;
var b = new Number(1);
console.log( Object.prototype.toString.call(a).slice(8,-1));
console.log(Object.prototype.toString.call(b).slice(8,-1));
複製程式碼
程式碼如下:
function is(obj,type) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type; } 定義一些變數做過測試,先來看看它們的typeof輸出:
複製程式碼
程式碼如下:
var a1=1;
var a2=Number(1 );
var b1="hello";
var b2=new String("hello");
var c1=[1,2,3];
var c2=new Array(1 ,2,3);
console.log("a1's typeof:" typeof(a1));
console.log("a2's typeof:" typeof(a2));
console.log(" b1's typeof:" typeof(b1));
console.log("b2's typeof:" typeof(b2));
console.log("c1's typeof:" typeof(c1));
console .log("c2's typeof:" typeof(c2));
輸出:
a1's typeof:number a2's typeof:object b1's typeof:string c1's 型態of:object c2's typeof:object
The newly created function we use is:
console.log("a1 is Number:" is(a1,"Number"));
console.log("a2 is Number:" is(a2,"Number"));
console.log( "b1 is String:" is(b1,"String"));
console.log("b2 is String:" is(b2,"String"));
console.log("c1 is Array :" is(c1,"Array"));
console.log("c2 is Array:" is(c2,"Array"));
Output:
a1 is Number:true
a2 is Number:true
b1 is String:true
b2 is String:true
c1 is Array:true
c2 is Array:true
Note: typeof It is not useless. The actual use is to detect whether a variable has been defined or assigned a value.
instanceof Description: Determine whether an object is a certain data type, or whether a variable is an instance of an object.
The instanceof operator is also powerless when used to compare two built-in type variables, and will also be dissatisfied with the result.
console.log("abc" instanceof String); / / false
console.log("abc" instanceof Object); // false
console.log(new String("abc") instanceof String); // true
console.log(new String( "abc") instanceof Object); // true
Reflects the relationship accurately only when comparing custom objects.
function Person() {}
function Man( ) {}
Man.prototype = new Person();
console.log(new Man() instanceof Man); // true
console.log(new Man() instanceof Person); // true