1忽媒、instanceof的作用是用來(lái)做檢測(cè)類型:
(1)instanceof可以檢測(cè)某個(gè)對(duì)象是不是另一個(gè)對(duì)象的實(shí)例;
var Person = function() {};
var student = new Person();
console.log(student instanceof Person); // true
復(fù)制代碼
(2)instanceof可以檢測(cè)父類型凑耻;
function Person() {};
function Student() {};
var p = new Person();
Student.prototype=p; //繼承原型
var s=new Student();
console.log(s instanceof Student); //true
console.log(s instanceof Person); //true
復(fù)制代碼
但是舒憾,instanceof不適合檢測(cè)一個(gè)對(duì)象本身的類型巷蚪。
2香拉、instanceof 檢測(cè)一個(gè)對(duì)象A是不是另一個(gè)對(duì)象B的實(shí)例的原理:
查看對(duì)象B的prototype指向的對(duì)象是否在對(duì)象A的[[prototype]]鏈上。如果在中狂,則返回true,如果不在則返回false凫碌。不過(guò)有一個(gè)特殊的情況,當(dāng)對(duì)象B的prototype為null將會(huì)報(bào)錯(cuò)(類似于空指針異常)吃型。
函數(shù)模擬A instanceof B:
function _instanceof(A, B) {
var O = B.prototype;// 取B的顯示原型
A = A.__proto__;// 取A的隱式原型
while (true) {
//Object.prototype.__proto__ === null
if (A === null)
return false;
if (O === A)// 這里重點(diǎn):當(dāng) O 嚴(yán)格等于 A 時(shí)证鸥,返回 true
return true;
A = A.__proto__;
}
}獲取更多資料QQ群786276452