Object.getPrototypeOf()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Object.getPrototypeOf() 静态方法返回指定对象的原型(即内部 [[Prototype]] 属性的值)。
尝试一下
const prototype = {};
const object = Object.create(prototype);
console.log(Object.getPrototypeOf(object) === prototype);
// 预期输出:true
语法
js
Object.getPrototypeOf(obj)
参数
obj-
要返回其原型的对象。
返回值
给定对象的原型,可能是 null。
示例
>使用 getPrototypeOf
js
const proto = {};
const obj = Object.create(proto);
Object.getPrototypeOf(obj) === proto; // true
非对象强制类型转换
在 ES5 中,如果 obj 参数不是对象,则会抛出 TypeError 异常。在 ES2015 中,该参数将被强制转换为 Object。
js
Object.getPrototypeOf("foo");
// TypeError: "foo" is not an object(ES5 代码)
Object.getPrototypeOf("foo");
// String.prototype(ES2015 代码)
规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-object.getprototypeof> |
浏览器兼容性
Loading…