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。离线整理了版式、链接和媒体显示。
