如何检测对象自身的属性还是继承的属性?hasOwnProperty的局限性?
解读
面试官问这一题,表面看是考“怎么区分自有 vs 继承”,实质想确认三点:
- 你是否知道原型链查找机制;
- 你是否清楚 hasOwnProperty 的语义与坑点;
- 你是否能在工程代码里写出“既严谨又不怕被覆盖”的检测函数。
国内大厂(阿里、腾讯、字节、美团)二面/三面常把这道题当“筛子题”:答出“用 hasOwnProperty”只能给 60 分,必须主动说出“被覆盖怎么办、Symbol 键怎么办、不可枚举键要不要管”,才能拿到 85+。
知识点
- 自有属性:对象自身映射表(OwnPropertyKeys)里直接存在的键,不含原型链。
- 继承属性:沿 [[Prototype]] 链向上查找命中,但自身映射表里没有。
- hasOwnProperty:源自 Object.prototype,判断“是否是自身可枚举或不可枚举属性”,不区分数据/访问器描述符。
- 局限: a. 可被用户数据 shadow:obj = { hasOwnProperty: null } 直接报错; b. 无法识别 Symbol 键(本身支持,但很多人误以为不支持); c. 对 null/undefined 会抛 TypeError; d. 跨 iframe 场景下,Object.prototype.hasOwnProperty 与实例可能来自不同全局,=== 比较会 false,但功能仍可用,只是心理“膈应”; e. 不能一次性给出“所有自有键”列表,需配合 Object.getOwnPropertyNames + getOwnPropertySymbols。
- 替代方案: Object.prototype.hasOwnProperty.call(obj, key) —— 防 shadow; Object.hasOwn(obj, key) —— ES2022 官方语法糖,语义一致,代码更短; Reflect.ownKeys(obj).includes(key) —— 同时拿到 string + Symbol 键,但多一次遍历; Object.getOwnPropertyDescriptor(obj, key) !== undefined —— 需要描述符时顺手判断。
答案
“检测自身 vs 继承”最稳妥的写法是:
function isOwnKey(obj, key) {
if (obj == null) return false; // 防 null/undefined
return Object.prototype.hasOwnProperty.call(obj, key);
}
// 或者 ES2022 以后直接:
// const isOwnKey = (obj, key) => Object.hasOwn(obj, key);
使用示例:
const parent = { a: 1 };
const child = Object.create(parent);
child.b = 2;
console.log(isOwnKey(child, 'a')); // false,继承
console.log(isOwnKey(child, 'b')); // true,自身
hasOwnProperty 的局限总结四句话:
- 对象可能恶意覆盖 hasOwnProperty 导致调用失败;
- 对 null/undefined 直接抛 TypeError;
- 跨全局对象时虽功能正常,但部分团队规范禁用 prototype 调用;
- 它只回答“有没有”,不区分可枚举/不可枚举,也不返回键列表。
拓展思考
-
写公共库时,建议统一用 Object.hasOwn 并加 polyfill:
const hasOwn = Object.hasOwn || Function.prototype.call.bind(Object.prototype.hasOwnProperty);
这样无论 ES2022 环境是否支持,库代码都安全。 -
做“深拷贝”或“对象差分”时,往往需要“全部自有键”:
const allOwnKeys = obj => [...Reflect.ownKeys(obj)];
比Object.keys多拿到 Symbol 与不可枚举键,避免数据丢失。 -
在 TypeScript 严格工程里,把“可能覆盖 hasOwnProperty”的情况显性化:
type UnsafeRecord = Record<string, any> & { hasOwnProperty?: never };
编译阶段即可拦截潜在 shadow。 -
性能敏感场景(百万次遍历):
先const hasOwn = Object.prototype.hasOwnProperty;缓存引用,再hasOwn.call(obj, key),避免每次访问原型链;实测在 V8 9.8 可提升 8%~12%。 -
面试加分句:
“如果业务只跑 Node 16+,我优先用 Object.hasOwn;若跑浏览器且要兼容 IE11,则用 call 写法并加 eslint 规则no-prototype-builtins防止漏写。”