一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情。
instanceof
用于检测构造函数和prototype属性是否出现在某个实例对象的原型链上。
语法:object(某个实例对象) instanceof constructor(某个构造函数)
// 定义构造函数
function C () {}
function D () {}
// 实例化一个 o 对象
var o = new C()
// true,true --> C.prototype 在 o 的原型链上
console.log(o instanceof C, o.__proto__ === C.prototype, '此时 o 的 __proto__:', o.__proto__, '此时 C 的 prototype:', C.prototype)
// false,false --> D.prototype 不在 o 的原型链上
console.log(o instanceof D, o.__proto__ === D.prototype)
// true true --> Object.prototype 在 o 的原型链上
console.log(o instanceof Object, o.__proto__.__proto__ === Object.prototype)
手写instanceof
//方法一:
function myinstanceof(source,target){
if(!['function','object'].includes(typeof source || source === null))
let proto = Object.getPrototypeOf(source)
while(true){
if(proto == null) return false;
if(proto == target.prototype) return true;
proto = object.getPrototypeOf(proto)
}
}
console.log(copyInstanceof("111", String)); // false console.log(copyInstanceof(new String("111"), String)); // true
//方法二
function _instanceof (left, right) {
let _proto = left.__proto__;
prototype = right.prototype;
while(true) {
// 直接就找到头了么?没有,进行下一步
if(_proto === null) {
return false
}
// 是不是相等,相等就是找到了
if(_proto === prototype) {
return true
}
// 前两个都不满足那就接着向上找
_proto = _proto.__proto__
}
}