handler.apply()
方法用于拦截函数的调用。
此交互式示例的源代码存储在GitHub存储库中。 如果您想为交互式示例项目做出贡献,请克隆 https://github.com/mdn/interactive-examples 并向我们发起拉取请求
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"
// 6
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) [[Call]] |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) [[Call]] |
Draft |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apply | Chrome Full support 49 | Edge Full support 12 | Firefox Full support 18 | IE No support No | Opera Full support 36 | Safari Full support 10 | WebView Android Full support 49 | Chrome Android Full support 49 | Edge Mobile Full support Yes | Firefox Android Full support 18 | Opera Android Full support 36 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |