// 使用方式
function Car(color) {
this.color = color
this.sayColor = function () {
console.log(this.color)
}
}
// const cc = new Car('red')
// console.log(cc instanceof Car)
/**
* 重点是分为基本数据类型和引用数据类型判断
* 引用数据类型中,需要判断对象(child)的原型链是否相等
* @param child 实例化对象
* @param parentFn 构造函数(类)
* @returns {boolean} true/false
*/
function myInstanceof(child, parentFn) {
const baseType = ['string', 'number', 'undefined', 'boolean', 'symbol']
if (baseType.includes(typeof child)) return true
let childProto = child.__proto__
const parentPrototype = parentFn.prototype
while (true) {
if (!childProto) return false
if (childProto === parentPrototype) return true
childProto = childProto.__proto__
}
}
const cc = new Car('red')
console.log(myInstanceof(cc, Car))
JS手写instanceof实现方式
最新推荐文章于 2025-02-25 20:54:35 发布