如何拦截带有函数的 JS 代理中的排序函数?
How do I intercept sort function within a JS proxy with a function?
我之前的相关问题:
鉴于代理:
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
函数中捕获不同的参数,但找不到正确的参数。
解决方案类似于:
我return一个访问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 );
}
我之前的相关问题:
鉴于代理:
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
函数中捕获不同的参数,但找不到正确的参数。
解决方案类似于:
我return一个访问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 );
}