Javascript 在 Node.js 中使用具有不同签名的函数
Javascript in Node.js using functions with different signatures
query(userOptions)
和 query(...args)
有什么区别?我知道它们可能是同一个函数调用的重载,但我不确定它们实际上是如何被调用的,或者在调用程序 select 的什么情况下使用了哪个重载,尤其是 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);
query(userOptions)
和 query(...args)
有什么区别?我知道它们可能是同一个函数调用的重载,但我不确定它们实际上是如何被调用的,或者在调用程序 select 的什么情况下使用了哪个重载,尤其是 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);