首先是查资料,MDN的解释是:
这个方法可以用来检测一个对象是否含有特定的自身属性
语法:obj.hasOwnProperty(prop)
参数:要检测的属性 字符串 名称或者 Symbol
返回值: 用来判断某个对象是否含有指定的属性的 Boolean
直接上代码来个示例:
function ObjWithProto(){ this.foo = 'foo_val' } ObjWithProto.prototype.bar = 'bar_val' var dict = new ObjWithProto() dict.foobar = 'foobar_val' dict.hasOwnProperty('foo') // true dict.hasOwnProperty('foobar') // true dict.hasOwnProperty('bar') // false
再来看 for…in , 遍历一个对象的可枚举属性
for(let i in dict){ console.log(i) } //foo // foobar // bar //原型链上的bar也获取到了
为了遍历一个对象的所有属性时忽略掉继承属性,使用hasOwnProperty()来过滤该对象上的继承属性。
for(let i in dict){ if(dict.hasOwnProperty(i)){ console.log(i) } } //foo //foobar
再来看看原型连上的一个继承
function ObjWithProto(){ this.foo = 'foo_val' } ObjWithProto.prototype.bar = 'bar_val' function Person(){ this.name = 'Person_name' } Person.prototype = new ObjWithProto() var _child = new Person() for(let i in _child){ console.log(i) } console.log('------ this is a line -------') for(let i in _child){ if(_child.hasOwnProperty(i)){ console.log(i) } } _child.hasOwnProperty('name') // true _child.hasOwnProperty('foo') // false _child.hasOwnProperty('bar') // false //name //foo //bar //------ this is a line ------- //name
用for...in循环会获取到原型链上的可枚举属性,不过可以使用hasOwnProperty()方法过滤掉。
链接:https://www.imooc.com/article/25415