handler.apply()

handler.apply() 方法是 [[Call]] 对象内部方法 的陷阱,用于函数调用等操作。

¥The handler.apply() method is a trap for the [[Call]] object internal method, which is used by operations such as function calls.

Try it

语法

¥Syntax

js
new Proxy(target, {
  apply(target, thisArg, argumentsList) {
  }
});

参数

¥Parameters

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

¥The following parameters are passed to the apply() method. this is bound to the handler.

target

目标可调用对象。

thisArg

调用的 this 参数。

argumentsList

调用的参数列表。

返回值

¥Return value

apply() 方法可以返回任何值。

¥The apply() method can return any value.

描述

¥Description

拦截

¥Interceptions

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

¥This trap can intercept these operations:

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

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

不变量

¥Invariants

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

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

  • target 本身必须是可调用的。也就是说,它必须是一个函数对象。

示例

¥Examples

捕获函数调用

¥Trapping a function call

以下代码捕获函数调用。

¥The following code traps a function call.

js
const p = new Proxy(function () {}, {
  apply(target, thisArg, argumentsList) {
    console.log(`called: ${argumentsList}`);
    return argumentsList[0] + argumentsList[1] + argumentsList[2];
  },
});

console.log(p(1, 2, 3)); // "called: 1,2,3"
// 6

规范

Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看