通过 path.resolve.apply(this, ...) 调用 path.resolve() 有什么效果?

What is the effect of invoking path.resolve() via path.resolve.apply(this, ...)?

在Azure Pipelines任务库中,有一个call to path.resolve() via apply() 我不是很明白:

var absolutePath = path.resolve.apply(this, pathSegments);

其中 pathSegments: any[]

以上代码是在模块范围内导出的函数中,因此(如果我理解正确)this 将引用模块本身。但是我不知道通过 apply 调用而不是直接调用 path.resolve() 的效果是什么。谁能解释一下?

上下文:我怀疑这可能与模拟有关 - 在等效模拟模块中有一个 similar function,它使用 path.posix.resolve.apply()。我的根本问题是,当我调用模拟的 tl.resolve('') - 通过 tl.filePathSupplied() 间接调用 - 它 returns 实际的 cwd 而不是通过 TaskLibAnswers.

模拟的那个

任何函数的 .apply() 方法都有两个特点:

  1. 它允许您在调用函数时设置 this 值。
  2. 它允许您传递任意参数数组,当函数被调用时,这些参数将被解压缩为实际参数(而不是数组)。

在这种情况下,这里可能使用了功能 #2,因为 path.resolve() 接受任意数量的参数。如果您没有使用最新版本的 node.js 或编码到较低级别的 Javascript 支持,因此没有扩展运算符,那么 .apply() 将是自然的方式当参数以数组形式传递给您时,将任意数量的参数传递给函数。

如果您查看 source for the path module 并找到 resolve() 函数的代码,您会发现它根本不使用 this 值,因此 path 对象仅用作命名空间对象。因此,您可以将 this 的任何值发送到 resolve 函数中,这不会有任何区别。

因此,代码使用 .apply() 可能不是为了设置 this 的值,而是为了将任意参数数组传递给函数。

But I'm at a loss as to what is the effect of calling via apply rather than just calling path.resolve() directly. Can anyone explain?

如果您向我们展示了更多周围的代码,我们可以更确定地回答,但 pathSegments 变量似乎已经是此代码要传递给 path.resolve()。如果这是一个任意数组,那么将该数组作为单独的参数传递给 path.resolve() 的两种最简单的方法是:

path.resolve.apply(path, pathSegments)

path.resolve(...pathSegments)

如果编写此代码时考虑的是没有 ... 语法的旧目标,那么 .apply() 选项将是最简单的方法。