我以前的相关问题:我如何在JS代理中拦截排序函数?
给定代理:
function sort(customSort) {
/* Write logs */
console.log("Intercepted sort")
return this.sort(customSort);
}
function get( target, prop, receiver ) {
if (prop === 'sort') {
/* How to capture custom sort?*/
return sort.bind(target);
}
console.log("Intercepted get")
return Reflect.get( target, prop, receiver );
}
var handler = {
get
};
var proxy = new Proxy( new Array(...[7,1,2,3,4,5]), handler );
现在我添加了一个自定义排序函数:
console.log(proxy.sort((a,b) => .... /* e.g., a-b */))
我无法理解如何捕获函数,将其传递给代理排序函数。我试着在get
函数中捕获不同的参数,但找不到正确的参数。
解决方案类似于:如何排序数组的一部分?在给定索引之间
返回访问argument[0]
function sort(customSort) {
/* Write logs */
console.log("Intercepted sort")
return this.sort(customSort);
}
function get( target, prop, receiver ) {
if (prop === 'sort') {
/* How to capture custom sort?*/
return function(customSort) => {
return this.sort(customSort || ((a,b) => a-b) )
}
}
console.log("Intercepted get")
return Reflect.get( target, prop, receiver );
}