面试题 - 手写 instanceof
instanceof 的作用
instanceof
运算符返回一个布尔值,表示对象是否为某个构造函数的实例(包括继承而来)。
instanceof
运算符用于检测: 某个实例对象的原型链上,是否有出现某个构造函数的 prototype 属性。
换句话说就是,顺着实例对象
的隐式原型一层层往上找,看能否找到某个构造函数
的显式原型。如果能,返回 true
,否则返回 false
。
例如:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car); // expected output: true
console.log(auto instanceof Object); // expected output: true
手写 myInstanceOf 函数
function myInstanceOf(obj, clas) {
let pointer = obj
while(pointer) {
if(pointer === clas.prototype) {
return true
}
pointer = pointer.__proto__
}
return false
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2021-04-11 JS 之事件
2021-04-11 JS基础总结 - this 指向