Reflect.setPrototypeOf()

Reflect.setPrototypeOf() 静态方法与 Object.setPrototypeOf() 类似,但返回 Boolean。它设置指定对象的原型(即内部 [[Prototype]] 属性)。

¥The Reflect.setPrototypeOf() static method is like Object.setPrototypeOf() but returns a Boolean. It sets the prototype (i.e., the internal [[Prototype]] property) of a specified object.

Try it

语法

¥Syntax

js
Reflect.setPrototypeOf(target, prototype)

参数

¥Parameters

target

要设置其原型的目标对象。

prototype

对象的新原型(对象或 null)。

返回值

¥Return value

Boolean 表示原型是否设置成功。

¥A Boolean indicating whether or not the prototype was successfully set.

例外情况

¥Exceptions

TypeError

如果 target 不是对象或者 prototype 既不是对象也不是 null,则抛出该异常。

描述

¥Description

Reflect.setPrototypeOf() 提供了设置对象原型的反射语义。在非常低的级别,设置原型返回一个布尔值(与 代理处理程序 的情况一样)。Object.setPrototypeOf() 提供了几乎相同的语义,但如果状态为 false(操作不成功),它会抛出 TypeError,而 Reflect.setPrototypeOf() 则直接返回状态。

¥Reflect.setPrototypeOf() provides the reflective semantic of setting the prototype of an object. At the very low level, setting the prototype returns a boolean (as is the case with the proxy handler). Object.setPrototypeOf() provides nearly the same semantic, but it throws a TypeError if the status is false (the operation was unsuccessful), while Reflect.setPrototypeOf() directly returns the status.

Reflect.setPrototypeOf() 调用 target[[SetPrototypeOf]] 对象内部方法

¥Reflect.setPrototypeOf() invokes the [[SetPrototypeOf]] object internal method of target.

示例

¥Examples

使用 Reflect.setPrototypeOf()

¥Using Reflect.setPrototypeOf()

js
Reflect.setPrototypeOf({}, Object.prototype); // true

// It can change an object's [[Prototype]] to null.
Reflect.setPrototypeOf({}, null); // true

// Returns false if target is not extensible.
Reflect.setPrototypeOf(Object.freeze({}), null); // false

// Returns false if it cause a prototype chain cycle.
const target = {};
const proto = Object.create(target);
Reflect.setPrototypeOf(target, proto); // false

规范

Specification
ECMAScript Language Specification
# sec-reflect.setprototypeof

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看