hasOwnProperty和in和instanceof的使用
2022/7/4 23:25:11
本文主要是介绍hasOwnProperty和in和instanceof的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.hasOwnProperty方法是用来检测当前属性是否为对象的私有属性(不仅要有这个属性,而且必须还是私有的才可以),该方法仅用于判断自身对象,不会查找原型链。
如下案例
function B() { this.age = 18; } B.prototype.name = "b";//在原型对象上添加name属性 const b = new B(); console.log(b.hasOwnProperty("name")); //false console.log(b.hasOwnProperty("age")); //true b.name = "c";//在实例本身添加name属性 console.log(b.hasOwnProperty("name")); //true2.in:检测当前对象是否存在某个属性(不管当前这个属性是对象的私有属性还是公有属性,只要有结果就是TRUE)
function B() { this.age = 18; } B.prototype.name = "b"; const b = new B(); console.log("name" in B); //true console.log("age" in B); //false console.log("name" in b); //true console.log("age" in b); //true
3.instanceof方法是判断某个对象是否由某个构造函数构建。
如A instanceof B,判断A对象是否由B构造函数创建。
通过__proto__一层层向上找,直到找到或找不到
const a = {}; function B() {} function myInstanceof(target, obj) { let p = target; while (p) { if (p === obj.prototype) { return true; } p = p.__proto__; } return false; } let b = new B(); console.log(myInstanceof(a, Function)); //false console.log(myInstanceof(a, Object)); //true console.log(myInstanceof(B, Function)); //true console.log(myInstanceof(B, Object)); //true console.log(myInstanceof(b, B)); //true console.log(myInstanceof(b, Function)); //false console.log(myInstanceof(b, Object)); //true
一般来说,js中的对象最终都是Object构造出来的。
因此 xxx instanceof Object的结果都是true.
这篇关于hasOwnProperty和in和instanceof的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升