hasOwnProperty 是 JavaScript 中用于判断属性是否为对象自身(非继承)的布尔方法,仅检查自有属性,不受属性值为 null/undefined 等影响;正确用法为 obj.hasOwnProperty('prop'),被覆盖时需用 Object.prototype.hasOwnProperty.call(obj, 'prop'),ES2022 起推荐使用更安全的 Object.hasOwn(obj, 'prop')。

hasOwnProperty 是 JavaScript 中用于判断某个属性是否直接定义在对象自身(而非继承自原型链)的可靠方法。它返回布尔值,且不会受属性值为 null、undefined 或 false 等“假值”影响,只关注属性是否存在且属于对象自身。
基本用法:调用对象自身的 hasOwnProperty 方法
必须通过对象实例调用,不能直接调用 Object.prototype.hasOwnProperty 并传入对象(除非显式绑定),否则可能被覆盖或出错。
- ✅ 正确写法:
obj.hasOwnProperty('prop') - ❌ 错误写法:
hasOwnProperty('prop')(未定义)或Object.hasOwnProperty('prop')(静态调用,不适用) - ⚠️ 注意:如果对象自身重写了
hasOwnProperty方法(极少见),会导致误判,此时可用Object.prototype.hasOwnProperty.call(obj, 'prop')绕过
为什么不能用 in 操作符或直接访问判断?
in 操作符会查找整个原型链,obj.prop !== undefined 无法区分属性不存在 vs 属性存在但值为 undefined,而 hasOwnProperty 明确限定作用域。
-
'toString' in {}→true(来自 Object.prototype),但{}.hasOwnProperty('toString')→false -
const obj = { prop: undefined }; obj.prop !== undefined→false,但obj.hasOwnProperty('prop')→true
实际使用中的常见场景
常用于遍历对象时过滤掉原型属性,或做安全的属性存在性校验。
- 安全遍历自有属性:
for (const key in obj) { if (obj.hasOwnProperty(key)) { /* 处理自有属性 */ } } - 配置合并前检查:
if (config.hasOwnProperty('timeout')) { useCustomTimeout = config.timeout; } - 避免意外覆盖原型方法:
if (!target.hasOwnProperty('save')) { target.save = fn; }
ES6+ 替代方案:Object.hasOwn(更现代、更安全)
Object.hasOwn(obj, 'prop') 是 hasOwnProperty 的推荐替代,从 ES2022 起标准化,能正确处理 null/undefined 输入,且不依赖对象自身方法:
-
Object.hasOwn(null, 'x')→false(而null.hasOwnProperty('x')报错) -
Object.hasOwn(obj, 'prop')内部等价于Object.prototype.hasOwnProperty.call(obj, 'prop') - 兼容性注意:Node.js ≥16.9 / Chrome ≥93 / Firefox ≥92 / Safari ≥15.4 支持;旧环境仍需用
hasOwnProperty或 polyfill

















