首先是查資料,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