in 運(yùn)算符和 hasOwnProperty 方法是檢查對(duì)象是否包含特定鍵的常用方法。
const person = {
name: 'foo'
}
console.log('name' in person) // true
console.log(person.hasOwnProperty('name')) // true
區(qū)別
對(duì)于繼承的屬性,in 將返回 true。顧名思義,hasOwnProperty 將檢查屬性是否為自身所有,并忽略繼承的屬性。
讓我們重用上一個(gè)示例中的 person 對(duì)象。由于它是一個(gè)具有內(nèi)置屬性的 JavaScript 對(duì)象,例如constructor,__proto__,因此以下檢查返回 true:
'constructor' in person // true
'__proto__' in person // true
'toString' in person // true
而 hasOwnProperty 在檢查這些屬性和方法時(shí)返回 false:
person.hasOwnProperty('constructor') // false
person.hasOwnProperty('__proto__') // false
person.hasOwnProperty('toString') // false
對(duì)于類的 get 和 set 方法,hasOwnProperty 也返回 false。
例如,我們有一個(gè)表示三角形的簡(jiǎn)單類:
class Triangle {
get vertices() {
return 3
}
}
// 創(chuàng)建新實(shí)例
const triangle = new Triangle()
盡管 vertices 是 triangle 的屬性:
triangle.vertices // 3
'vertices' in triangle // true
hasOwnProperty 仍然忽略它:
triangle.hasOwnProperty('vertices') // false
建議
要檢查屬性是否存在,請(qǐng)使用 hasOwnProperty。使用 in 檢查方法的存在。