query(userOptions)
和 query(...args)
有什么区别?我知道它们可能是同一个函数调用的重载,但我不确定它们将如何实际调用或在调用程序中的什么情况下选择使用哪个重载,尤其是 static
装饰。
class Gamedig {
constructor() {
this.queryRunner = new QueryRunner();
}
async query(userOptions) {
return await this.queryRunner.run(userOptions);
}
static getInstance() {
if (!singleton) singleton = new Gamedig();
return singleton;
}
static async query(...args) {
return await Gamedig.getInstance().query(...args);
}
}
最佳答案
static
表示该函数已分配给构造函数,即 Gamedig
。该函数被称为
Gamedig.query(...)
如果没有 static
,该函数在 Gamedig
的实例上是可访问的,即
var instance = new Gamedig();
instance.query(...);
JavaScript 不支持函数重载。
userOptions
vs ...args
与此无关。 rest parameter在函数定义中意味着该函数接受可变数量的参数,并且它们都收集在分配给该参数的数组中(args
在您的示例中)。
例子:
function foo(...bar) {
console.log(bar);
}
foo(1);
foo(1,2);
foo(1,2,3);
关于Node.js 中的 Javascript 使用具有不同签名的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416878/