最近開始在整理ES6/ES7/ES8/ES9
的知識點(已經上傳到 我的博客 上),碰到一些知識點是自己已經忘記(用得少的知識點),於是也重新複習了一遍。
這篇文章要複習的 instanceof
是我在整理過程中遇到的,那就整理下來吧,不然容易忘記。
要是哪裏寫得不妥,歡迎各位大佬指點。
1.定義
instanceof
運算符用於測試構造函數的prototype
屬性是否出現在對象的原型鏈中的任何位置。 —— MDN
簡單理解爲:instanceof
可以檢測一個實例是否屬於某種類型。
比如:
function F (){
// ...
}
let a = new F ();
a instanceof F; // true
a instanceof Object; // true 後面介紹原因
還可以在繼承關係中用來判斷一個實例是否屬於它的父類型。
比如:
function F (){};
function G (){};
function Q (){};
G.prototype = new F(); // 繼承
let a = new G();
a instanceof F; // true
a instanceof G; // true
a instanceof Q; // false
2.使用方法
語法爲: object instanceof constructor
。
object
: 需要測試的函數constructor
: 構造函數
即:用instanceof
運算符來檢測constructor.prototype
是否存在參數object
的原型鏈。
function F (){};
function G (){};
let a = new F ();
a instanceof F; // true 因爲:Object.getPrototypeOf(a) === F.prototype
a instanceof Q; // false 因爲:F.prototype不在a的原型鏈上
a instanceof Object; // true 因爲:Object.prototype.isPrototypeOf(a)返回true
F.prototype instanceof Object; // true,同上
注意:
a instanceof F
返回true
以後,不一定永遠都都返回爲true
,F.prototype
屬性的值有可能會改變。- 原表達式
a
的值也會改變,比如a.__proto__ = {}
之後,a instanceof F
就會返回false
了。
檢測對象是不是特定構造函數的實例:
// 正確
if (!(obj instanceof F)) {
// ...
}
// 錯誤 因爲
if (!obj instanceof F); // 永遠返回false
// 因爲 !obj 在instanceof之前被處理 , 即一直使用一個布爾值檢測是否是F的實例
3.實現instanceof
/**
* 實現instanceof
* @param obj{Object} 需要測試的對象
* @param fun{Function} 構造函數
*/
function _instanceof(obj, fun) {
let f = fun.prototype; // 取B的顯示原型
obj = obj.__proto__; // 取A的隱式原型
while (true) {
//Object.prototype.__proto__ === null
if (obj === null)
return false;
if (f === obj) // 這裏重點:當 f 嚴格等於 obj 時,返回 true
return true;
obj = obj.__proto__;
}
}
4.instanceof 與 typeof 對比
相同:
instanceof
和typeof
都能用來判斷一個變量的類型。
區別:
instanceof
只能用來判斷對象、函數和數組,不能用來判斷字符串和數字等:
let a = {};
let b = function () {};
let c = [];
let d = 'hi';
let e = 123;
a instanceof Object; // true
b instanceof Object; // true
c instanceof Array; // true
d instanceof String; // false
e instanceof Number; // false
typeof
:用於判斷一個表達式的原始值,返回一個字符串。
typeof 42; // "number"
typeof 'blubber'; // "string"
typeof true; // "boolean"
typeof aa; // "undefined"
一般返回結果有:
- number
- boolean
- string
- function(函數)
- object(NULL,數組,對象)
- undefined。
判斷變量是否存在:
不能使用:
if(a){
//變量存在
}
// Uncaught ReferenceError: a is not defined
原因是如果變量未定義,就會報未定義的錯,而應該使用:
if(typeof a != 'undefined'){
//變量存在
}