【问题标题】:How do I intercept sort function within a JS proxy with a function?如何使用函数拦截 JS 代理中的排序函数?
【发布时间】:2021-12-07 22:22:10
【问题描述】:

我之前的相关问题:How do I intercept sort function within a JS proxy?

给定代理:

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 函数中捕获不同的参数,但找不到正确的参数。

【问题讨论】:

  • 你不只需要function sort() -> function sort(a, b)吗?我不确定代理与这里有什么关系。
  • 我实现的代理也做了一些其他的工作,这就是我需要代理的原因
  • 您需要它做什么?我无法理解您的期望是什么。你想做什么?
  • 代理中的排序功能还可以完成一些其他工作,例如写入日志。然后,我需要应用用户尝试执行的相同排序。即,用户需要忽略代理。

标签: javascript node.js javascript-proxy


【解决方案1】:

解决方案类似于:How to sort only part of array? between given indexes

我返回一个访问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 );
}

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多