js中的instanceof

js中的instanceof
概述
instanceof运算符⽤来判断⼀个构造函数的prototype属性所指向的对象是否存在另外⼀个要检测对象的原型链上
语法
obj instanceof Object;//true 实例obj在不在Object构造函数中
描述
instanceof 运算符⽤来检测 constructor.prototype 是否存在于参数 object 的原型链上。
实例
烟气道1.instanceof的普通的⽤法,obj instanceof Object 检测Object.prototype是否存在于参数obj的原型链上。Person的原型在p的原型链中
function Person(){};
var p =new Person();
console.log(p instanceof Person);//true
2.继承中判断实例是否属于它的⽗类
Student和Person都在s的原型链中
function Person(){};
function Student(){};
var p =new Person();
Student.prototype=p;//继承原型plc学习机
var s=new Student();
console.log(s instanceof Student);//true
console.log(s instanceof Person);//true
3.复杂⽤法
这⾥的案例要有熟练的原型链的认识才能理解
function Person() {}
console.log(Object instanceof Object);    //true
烧烤箱//第⼀个Object的原型链:Object=>
//Object.__proto__ => Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第⼆个Object的原型:Object=> Object.prototype
console.log(Function instanceof Function); //true
//第⼀个Function的原型链:Function=>Function.__proto__ => Function.prototype
//第⼆个Function的原型:Function=>Function.prototype
console.log(Function instanceof Object);  //true
/
/Function=>
//Function.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//Object => Object.prototype
console.log(Person instanceof Function);      //true
//Person=>Person.__proto__=>Function.prototype
//Function=>Function.prototype
console.log(String instanceof String);  //false
//第⼀个String的原型链:String=>
//String.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第⼆个String的原型链:String=>String.prototype
console.log(Boolean instanceof Boolean); //false
/
/第⼀个Boolean的原型链:Boolean=>
混纺纱//Boolean.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第⼆个Boolean的原型链:Boolean=>Boolean.prototype
console.log(Person instanceof Person); //false
//第⼀个Person的原型链:Person=>
//Person.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第⼆个Person的原型链:Person=>Person.prototype
//第⼆个Person的原型链:Person=>Person.prototype
总结
皮革涂饰剂
对应上述规范做个函数模拟A instanceof B:
function _instanceof(A, B) {
var O = B.prototype;// 取B的显⽰原型
eeg平台A = A.__proto__;// 取A的隐式原型
while (true) {
//Object.prototype.__proto__ === null
if (A === null)
return false;
if (O === A)// 这⾥重点:当 O 严格等于 A 时,返回 true            return true;
A = A.__proto__;
}
}

本文发布于:2024-09-23 18:23:15,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/1/277494.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:是否   原型   规范   存在   对象   判断   皮革   涂饰
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议