大网数据广告活动
Web 标准与前端开发

handler.apply()

· 52CE 我爱测

以下是传递给 apply 方法的参数,`this` 上下文绑定在 handler 对象上。

handler.apply() 方法用于拦截函数的调用。

JavaScript Demo: handler.apply()

function sum(a, b) {
  return a + b;
}

const handler = {
  apply: function (target, thisArg, argumentsList) {
    console.log(`Calculate sum: ${argumentsList}`);
    // Expected output: "Calculate sum: 1,2"

    return target(argumentsList[0], argumentsList[1]) * 10;
  },
};

const proxy1 = new Proxy(sum, handler);

console.log(sum(1, 2));
// Expected output: 3
console.log(proxy1(1, 2));
// Expected output: 30

语法

var p = new Proxy(target, {
  apply: function (target, thisArg, argumentsList) {},
});

参数

以下是传递给 apply 方法的参数,this 上下文绑定在 handler 对象上。

  • target
    • : 目标对象(函数)。
  • thisArg
    • : 被调用时的上下文对象。
  • argumentsList
    • : 被调用时的参数数组。

返回值

apply 方法可以返回任何值。

描述

handler.apply 方法用于拦截函数的调用。

拦截

该方法会拦截目标对象的以下操作:

  • proxy(...args)
  • Function.prototype.apply() 和 Function.prototype.call()
  • Reflect.apply()

约束

如果违反了以下约束,代理将抛出一个 TypeError:

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

示例

以下代码演示如何捕获函数的调用。

var p = new Proxy(function () {}, {
  apply: function (target, thisArg, argumentsList) {
    console.log("called: " + argumentsList.join(", "));
    return argumentsList[0] + argumentsList[1] + argumentsList[2];
  },
});

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

规范

浏览器兼容性

参见

  • Proxy
  • Proxy/Proxy
  • Function.prototype.apply
  • Function.prototype.call
  • Reflect.apply()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。