fn.apply(...) 未正确应用参数

问题描述 投票:0回答:1

我在一个应用程序中遇到一个案例,其中给出以下内容:

const myFuncs = {

  func1: (a, b) => console.log({ a, b }),
  func2: (x, y, z) => console.log({ x, y, z })
}

我有一个外部进程,它发送要执行的函数和参数数组。

例如:

api.post('/example', { fn: 'func1', args: [1, 2] });

接收端捕获该有效负载并将其应用于适当的功能:

const handler = (payload) => {

  const { fn, args } = payload;

  // do not try something that will fail
  if (typeof fn !== 'string' || Array.isArray(args)) {
    return;
  }

  const func = myFuncs[fn];

  if (func === undefined || typeof func !== 'function') {
    return;
  }

  // apply the arguments to the function
  func.apply(func, args);
}

我已经做了一百万次这样的事情,但是,在这个特定的应用程序中,我得到了以下结果:

api.post('/example', { fn: 'func1', args: [1,2] });
// console.logs => { a: [1,2], b: undefined }

api.post('/example', { fn: 'func2', args: [1,2,3] });
// console.logs => { x: [1,2,3], y: undefined, z: undefined }

我期待的地方:


api.post('/example', { fn: 'func1', args: [1,2] });
// console.logs => { a: 1, b: 2 }

api.post('/example', { fn: 'func2', args: [1,2,3] });
// console.logs => { x: 1, y: 2, z: 3 }

这是第一次发生此类事情。我尝试从 NodeJS 18 升级到 20,但没有成功。知道会发生什么吗?

更多背景:

这是一个简化的示例。实际上,我正在通过 IPC 将这个

{ fn: '', args: [] }
有效负载传递给电子进程。我不知道是否有什么事情是压倒一切的
Function.prototype.apply
,但我肯定不是,而且我无法想象有人会这样做(非常奇怪)。

javascript electron apply
1个回答
0
投票

在您的代码片段中,由于

return if Arrays.isArray(args)
的条件,函数将过早返回。 [1, 2] 确实会将 isArray 评估为
true

如果这个示例代表了您的用例,那么该方法实际上并没有达到 fn.apply 的程度,也不是问题所在。

(请原谅回复;由于声誉问题,我还不能发表评论。)

© www.soinside.com 2019 - 2024. All rights reserved.