typeof
只能檢測出undefined
,string
, number
, boolean
, symbol
, function
,object
返回值
- 基本類型,除 null 以外,均可以返回正確的結果。
- 引用類型,除 function 以外,一律返回 object 類型。
- null ,返回 object 類型。
- function 返回 function 類型。
原理
js 在底層存儲變量的時候,會在變量的機器碼的低位 1-3 位存儲其類型信息
- 000:對象
- 010:浮點數
- 100:字符串
- 110:布爾
- 1:整數
null
:所有機器碼均爲 0
undefined
:用 −230 整數來表示
typeof
在判斷 null
的時候由於 null
的所有機器碼均爲 0,因此直接被當做了對象來看待。
toString
const isType = type => target =>
Object.prototype.toString.call(target) === `[object ${type}]`;
const isArray = isType("Array");
const isRegExp = isType("RegExp");
const isNull = isType("Null");
instanceof
instanceof 運算符用於測試構造函數的 prototype 屬性是否出現在對象的原型鏈中的任何位置
function _instanceof(left, right) {
while (Object.getPrototypeOf(left) && right.prototype) {
if (Object.getPrototypeOf(left) === right.prototype) {
return true;
}
left = Object.getPrototypeOf(left);
}
return false;
}
實現的_instanceof
和直接使用 instanceof 對基本類型判斷表現不一致
[1] instanceof Array; // true
[1] instanceof Object; // true
"tom" instanceof String; //false
11 instanceof Number; //false
instanceof
運算符直接訪問的變量的原始值,不會自動建立包裝類。因此不能用來判斷基本類型值。
instanceof 只能用來判斷兩個對象是否屬於實例關係, 而不能判斷一個對象實例具體屬於哪種類型。
問題
instanceof
假定只有一個全局執行環境。如果網頁中包含多個框架,那實際上就存在兩個以上不同的全局執行環境,從而存在兩個以上不同版本的構造函數。如果你從一個框架向另一個框架傳入一個數組,那麼傳入的數組與在第二個框架中原生創建的數組分別具有各自不同的構造函數。
constructor
"s".constructor === String; // true
todo
- null 和 undefined 沒有 constructor 屬性,可以採用其他判斷方式
- 函數的 constructor 是不穩定的,這個主要體現在自定義對象上,當開發者重寫 prototype 後,原有的 constructor 引用會丟失,constructor 會默認爲 Object