handler.preventExtensions()

handler.preventExtensions() 方法是对 [[PreventExtensions]] 对象内部方法 的陷阱,被 Object.preventExtensions() 等操作使用。

¥The handler.preventExtensions() method is a trap for the [[PreventExtensions]] object internal method, which is used by operations such as Object.preventExtensions().

Try it

语法

¥Syntax

js
new Proxy(target, {
  preventExtensions(target) {
  }
})

参数

¥Parameters

以下参数传递给 preventExtensions() 方法。this 绑定到处理程序。

¥The following parameter is passed to the preventExtensions() method. this is bound to the handler.

target

目标对象。

返回值

¥Return value

preventExtensions() 方法必须返回一个 Boolean,指示操作是否成功。其他值为 强制转换为布尔值

¥The preventExtensions() method must return a Boolean indicating whether or not the operation was successful. Other values are coerced to booleans.

如果 [[PreventExtensions]] 内部方法返回 false,则许多操作(包括 Object.preventExtensions())会抛出 TypeError

¥Many operations, including Object.preventExtensions(), throw a TypeError if the [[PreventExtensions]] internal method returns false.

描述

¥Description

拦截

¥Interceptions

该陷阱可以拦截以下操作:

¥This trap can intercept these operations:

或调用 [[PreventExtensions]] 内部方法 的任何其他操作。

¥Or any other operation that invokes the [[PreventExtensions]] internal method.

不变量

¥Invariants

如果处理程序定义违反以下不变量之一,则代理的 [[PreventExtensions]] 内部方法将抛出 TypeError

¥The proxy's [[PreventExtensions]] internal method throws a TypeError if the handler definition violates one of the following invariants:

  • 如果目标对象上的 Reflect.isExtensible() 在调用 handler.preventExtensions() 后返回 false,则结果仅为 true

示例

¥Examples

捕获 preventExtensions

¥Trapping of preventExtensions

以下代码捕获 Object.preventExtensions()

¥The following code traps Object.preventExtensions().

js
const p = new Proxy(
  {},
  {
    preventExtensions(target) {
      console.log("called");
      Object.preventExtensions(target);
      return true;
    },
  },
);

console.log(Object.preventExtensions(p));
// "called"
// false

以下代码违反了不变量。

¥The following code violates the invariant.

js
const p = new Proxy(
  {},
  {
    preventExtensions(target) {
      return true;
    },
  },
);

Object.preventExtensions(p); // TypeError is thrown

规范

Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-preventextensions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看