您现在的位置: 365建站网 > 365文章 > hasOwnProperty 怎么区分自身属性和原型属性?这三种场景它会直接失效

hasOwnProperty 怎么区分自身属性和原型属性?这三种场景它会直接失效

文章来源:365jz.com 点击数:365 更新时间:2024-08-29 09:05

一、一句话定义:只看「自己的」,不看「继承的」

MDN 对它的定义非常干净:

The hasOwnProperty() method of Object instances returns a boolean indicating whether this object has the specified property as its own property (as opposed to inheriting it).

Description 段又补了三条边界,这三条正是日常判断失误的来源:

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object's prototype chain.
  • 值为 null / undefined 也算「有」——这跟 if (obj.x) 的判断完全不是一回事。
  • 继承来的一律 false,包括 toString 这种人人都有的方法。
  • 与 in 的分界:in 会走完整条原型链,hasOwnProperty 不会。

参数 prop 接受字符串名或 Symbol;返回值是布尔。官方例子直接给出对照组:

const example = {};
example.prop = "exists";
example.hasOwnProperty("prop");        // true
example.hasOwnProperty("toString");    // false
example.hasOwnProperty("hasOwnProperty"); // false

“prop” in example; // true
“toString” in example; // true
“hasOwnProperty” in example; // true

再看值不影响判定的那条:

example.prop = null;
example.hasOwnProperty("prop");     // true - own property exists with value of null
example.prop = undefined;
example.hasOwnProperty("prop");     // true - own property exists with value of undefined

做接口数据合并时特别常用:undefined 说明字段被显式传了空值,应该覆盖默认配置;字段压根不存在则应保留默认值。这两者的区别只能靠 hasOwnProperty 判断,靠值判断一律丢失。

二、数组下标也能用,但语义不是「越界」

Array 也是 Object,所以能继承到这个方法,官方举例:

const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
fruits.hasOwnProperty(3); // true ('Orange')
fruits.hasOwnProperty(4); // false - not defined

注意它判断的是「该索引属性是否存在」,不是「索引是否小于 length」。稀疏数组 [1,,3] 中间那个空洞 hasOwnProperty(1) 会返回 false,这是它比 length 判断更可靠的地方,也是遍历稀疏数组时避免算出 NaN 的关键。

自身属性与原型属性的放大镜示意图
放大镜只看对象自己的格子,原型链上的全部忽略

三、三种失效场景,官方逐个点名

场景一:属性名被覆盖。MDN 的措辞很直接——JavaScript does not protect the property name hasOwnProperty:

const foo = {
  hasOwnProperty() {
    return false;
  },
  bar: "Here be dragons",
};
foo.hasOwnProperty("bar"); // re-implementation always returns false

这不是理论风险。任何把外部 JSON 直接 Object.assign 或展开进对象的地方,只要数据里带一个 hasOwnProperty 键,你后面所有的存在性判断会集体变成 false,而错误还完全静默。

场景二:null 原型对象。手册原文:

null-prototype objects do not inherit from Object.prototype, making hasOwnProperty() inaccessible.

const foo = Object.create(null);
foo.prop = “exists”;
foo.hasOwnProperty(“prop”); // Uncaught TypeError: foo.hasOwnProperty is not a function

用 Object.create(null) 当纯字典(避免原型污染)是很常见的写法,但它同时拿掉了这个方法,foo.hasOwnProperty(...) 直接抛 TypeError。

场景三:误以为它只管可枚举属性。在 for...in 里包一层是标准写法:

const buz = { fog: "stack" };
for (const name in buz) {
  if (buz.hasOwnProperty(name)) {
    console.log(`this is fog (${name}) for sure. Value: ${buz[name]}`);
  } else {
    console.log(name); // toString or something else
  }
}

但官方紧跟了一句澄清:

Note that the for...in loop only iterates enumerable items: the absence of non-enumerable properties emitted from the loop does not imply that hasOwnProperty itself is confined strictly to enumerable items. You can iterate over non-enumerable properties with Object.getOwnPropertyNames().

也就是说 hasOwnProperty 本身不区分可枚举,不可枚举的自有属性它照样返回 true;是 for...in 帮你过滤了。想拿到不可枚举的自有属性,得走 Object.getOwnPropertyNames()。

四、正确写法:优先 Object.hasOwn()

MDN 在开头就给了 Note:Object.hasOwn() is recommended over hasOwnProperty(), in browsers where it is supported。针对场景一、二,官方给了三种绕法:

const foo = { bar: "Here be dragons" };
// Use Object.hasOwn() method - recommended
Object.hasOwn(foo, "bar");                              // true
// Use the hasOwnProperty property from the Object prototype
Object.prototype.hasOwnProperty.call(foo, "bar");       // true
// Use another Object's hasOwnProperty
// and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, "bar");                   // true

并且补了一句实现层面的说明:前两种写法不会新建对象,第三种为了造一个空字典而多分配了一个临时对象。对 null 原型对象,官方给的解法同上——优先 Object.hasOwn(),否则借外部对象的 hasOwnProperty。

兼容性方面,这一族能力的基线标注为 Widely available,官方写明「It's been available across browsers since July 2015」,hasOwnProperty 本体属于 ECMAScript 语言规范里 sec-object.prototype.hasownproperty 一节。

五、写代码时直接照这三条办

  1. 能确定运行环境支持时,一律用 Object.hasOwn(obj, key),它不吃 this、不怕键名覆盖、null 原型对象照常可用;特性检测本身也可以用它来写(Object.hasOwn(HTMLTemplateElement.prototype, "shadowRootMode") 就是官方文档里的实际用法)。
  2. 需要兼容老环境时,写成 Object.prototype.hasOwnProperty.call(obj, key),永远不要写 obj.hasOwnProperty(key)。
  3. 遍历 for...in 时把它包进 if 只是过滤原型属性,不等于过滤可枚举;需要完整自有属性清单时用 Object.getOwnPropertyNames() 或 Reflect.ownKeys()。

参考来源:MDN Web Docs《Object.prototype.hasOwnProperty()》(页面最后修订 2025-07-20)。

生产内容,同时打通搜索引擎(SEO)与AI搜索引擎(GEO)流量入口的软件! 点击进入365建站器 »