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() 方法必须返回布尔值。

¥The preventExtensions() method must return a boolean value.

描述

¥Description

拦截

¥Interceptions

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

¥This trap can intercept these operations:

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

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

不变量

¥Invariants

如果违反以下不变量,则陷阱在调用时会抛出 TypeError

¥If the following invariants are violated, the trap throws a TypeError when invoked.

  • 如果 Object.isExtensible(proxy)false,则 Object.preventExtensions(proxy) 仅返回 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

也可以看看