[Javascript] 'in' keyword vs hasOwnProperty

Main difference is that

in keyword will check on object prototype chain as well

but hasOwnProperty won't check agaist prototype chain

 

const obj = {}
'constructor' in obj // true
'__proto__' in obj // true
'hasOwnProperty' in obj // true

obj.hasOwnProperty('constructor') // false
obj.hasOwnProperty('__proto__') // false
obj.hasOwnProperty('hasOwnProperty') // false

 

posted @ 2024-11-23 22:45  Zhentiw  阅读(7)  评论(0)    收藏  举报