var arr = [1, 2, 3]
Array.isArray(arr) // true
Object.prototype.toString.call(arr) // [object Array]
arr.constructor === Array // true
arr instanceof Array // true
Array.prototype.isPrototypeOf(arr)
Object.getPrototypeOf(arr) === Array.prototype
理解:
a instanceof b (variable instanceof constructor) a是对象,b是构造函数
- 使用:判断某个对象是否属于某个构造函数
- 原理:判断b的prototype是否在a的原型链上
a.isPrototypeOf(b)
同理可以看出:
- Array.prototype.isPrototypeOf(arr) 是在判断Array的prototype是否在arr的原型链上
Object.getPrototypeOf(a)
手写instanceof
function instanceOf(obj, construtor) {
const prototype = construtor.prototype
let proto = Object.getPrototypeOf(obj)
let flag = true
while(flag) {
if(proto === null) {
return false
}
if(proto === prototype) {
return true
}
proto = Object.getPrototypeOf(proto)
}
}