英文:
Invoke class instance like function
问题
在TypeScript中,是否可以定义一个类,使您可以像调用方法名一样调用“default”方法,例如下面是我所指的示例。
export class StringBuilder {
private inner = '';
// ...
public ToString(): string {
return this.inner;
}
}
然后假设在某个调用代码中,我有该类的一个实例,并希望以这种方式调用它:
const sb = new StringBuilder('xample');
sb(0, 'e');
console.log(sb.ToString()); // 假设逻辑在索引0处添加字符串,因此应该记录“example”
是否可以定义一个方法,接受这两个参数,在使用实例本身时会被调用,看起来像是我需要一个调用签名,但我在找到适用于这种情况的示例时遇到了困难。
这是为一个项目而做的,我正在处理一些从旧的VB.NET代码转码而来的TypeScript代码,因此我正试图编写一个实现。
英文:
In TypesScript, is it possible to define a class such that you could invoke a 'default' method as if the instance is a method name? Here's an example of what I mean.
export class StringBuilder {
private inner = '';
...
public ToString(): string {
return inner;
}
}
Then let's say in some calling code, I have an instance of the class and I want to call it this way:
const sb = new StringBuilder('xample');
sb(0, 'e');
console.log(sb.ToString()); // assume the logic adds the string at index 0, so should log 'example'
Is it possible to define a method that would accept those two arguments that would be invoked when using the instance itself like that?
It seems like a call signature is what I need, but I'm struggling to find examples that suit this scenario.
This is for a project where I'm handling some TypeScript code that is transcoded from legacy VB.NET code, so I'm trying to code to an implementation.
答案1
得分: 0
请看这个:
尝试这个:
```typescript
class Callable extends Function {
private _bound;
constructor() {
super('...args', 'return this._bound.call(...args)');
this._bound = this.bind(this)
return this._bound
}
}
class StringBuilder extends Callable {
call(...args: any[]) {
console.log(...args);
}
}
const sb = new StringBuilder();
sb(0, 'e');
<details>
<summary>英文:</summary>
Try this:
```typescript
class Callable extends Function {
private _bound;
constructor() {
super('...args', 'return this._bound.call(...args)');
this._bound = this.bind(this)
return this._bound
}
}
class StringBuilder extends Callable {
call(...args: any[]) {
console.log(...args);
}
}
const sb = new StringBuilder();
sb(0, 'e');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论