object.hasown只能检测对象自身属性,不查原型链,故对内置实例(如string、array)能准确识别自有属性(如custom、"0"、tag),但无法检测其原型方法(如split、push),后者需用in或typeof判断。

支持,但要注意检测对象和属性的归属关系——Object.hasOwn 只能检测目标对象自身是否拥有某个属性,不能跨原型链查找,所以对内置对象(如 String、Array、Date 的实例)要区分“实例自有属性”和“原型方法”。
检测内置对象实例的自有属性
内置构造函数创建的实例(如 new String()、new Array()、new Date())本身可能有自有属性,Object.hasOwn 能准确识别:
- 字符串包装对象可带自有属性:
const str = new String("hello"); str.custom = true; Object.hasOwn(str, "custom") → true - 数组实例的数值索引是自有属性:
const arr = [10]; Object.hasOwn(arr, "0") → true(注意传字符串 "0",不是数字 0) - Date 实例若手动添加属性,也能被检测到:
const d = new Date(); d.tag = "log"; Object.hasOwn(d, "tag") → true
不能检测原型上的内置方法
像 split、push、toISOString 这类方法定义在原型上,不是实例自身的属性:
-
const str = new String("a"); Object.hasOwn(str, "split") → false(split 在 String.prototype 上) -
const arr = []; Object.hasOwn(arr, "push") → false(push 在 Array.prototype 上) - 想查原型方法是否存在,应使用
"split" in str或typeof str.split === "function",而非 Object.hasOwn
对内置构造函数本身也适用
Function、Array、Object 等本身也是对象,Object.hasOwn 可用于检查它们自身的属性(非原型继承):
-
Object.hasOwn(Array, "isArray") → true(isArray 是 Array 函数自身的静态方法) Object.hasOwn(String, "raw") → trueObject.hasOwn(Date, "now") → true- 但
Object.hasOwn(Array, "prototype") → false,因为 prototype 是不可枚举自有属性,而 Object.hasOwn 支持不可枚举属性 —— 实际上它返回 true,因为Array.prototype确实是 Array 函数自身的属性(可通过Object.getOwnPropertyNames(Array)查看)
注意事项
使用时需确保第一个参数是对象类型,否则会抛 TypeError:
- 原始值(如
"hello"、42、true)不能直接传入 —— 它们不是对象,Object.hasOwn 会报错 - 若需检测原始值“对应包装对象”的自有属性,必须显式转为对象:
Object.hasOwn(Object("hello"), "length") → true - Symbol 属性同样支持,包括内置 Symbol(如
Symbol.iterator),只要它是目标对象自身的











