美文网首页
js原型in与hasOwnProperty的属性检测差异

js原型in与hasOwnProperty的属性检测差异

作者: 小李不小 | 来源:发表于2020-10-20 16:26 被阅读0次
var a={name:'1'};
var b={name2:'2'};
 Object.setPrototypeOf(a,b);
 console.dir(a)
 // in与hasOwnProperty的属性检测差异
 // in 能把原型上的属性全部检查出来
 // hasOwnProperty 只能查到属于自己的属性和方法
 console.log('name' in a)//true


 console.log(a.hasOwnProperty('name2')) //false  name2不是属于a自身的属性,而是原型上的属性,所有false

 console.log(a.hasOwnProperty('name')) //true
//name是属于a自身的属性,不是原型上的属性,所有true

相关文章

网友评论

      本文标题:js原型in与hasOwnProperty的属性检测差异

      本文链接:https://www.haomeiwen.com/subject/lhadektx.html