Abh*_*ava 3 javascript function typescript
我想在打字稿中使用函数链.
考虑一堂课
export class numbOp(){
private n;
constructor(int num){
this.n = num;
}
public add(inc = 1){
this.n = this.n + inc;
}
}
Run Code Online (Sandbox Code Playgroud)
我如何使用它(1)
let finalNumber = new numbOp(3);
console.log(finalNumber) // Output: 3
Run Code Online (Sandbox Code Playgroud)
我如何使用它作为(2)
let finalNumber = new numbOp(3).add();
console.log(finalNumber) // Output: 4
Run Code Online (Sandbox Code Playgroud)
我如何使用它(3)
let finalNumber = new numbOp(3).add().add();
console.log(finalNumber) // Output: 5
Run Code Online (Sandbox Code Playgroud)
我如何使用它(4)
let finalNumber = new numbOp(3).add().add(2).toString();
console.log(finalNumber) // Output: "6"
Run Code Online (Sandbox Code Playgroud)
请帮助我实现这一目标.提前致谢 :)
您只需this要从想要链接的函数返回
class numbOp {
private n: number;
constructor(num: number) {
this.n = num;
}
public add(inc = 1) : this { // annotation not necessary added to address comments
this.n = this.n + inc;
return this;
}
toString() {
return this.n;
}
}
let finalNumber = new numbOp(3);
console.log(finalNumber + "") // Output: 3
//How do I use it as (2)
let finalNumber2 = new numbOp(3).add();
console.log(finalNumber2 + "") // Output: 4
//How do I use it as (3)
let finalNumber3 = new numbOp(3).add().add();
console.log(finalNumber3 + "") // Output: 5
//How do I use it as (4)
let finalNumber4 = new numbOp(3).add().add(2).toString();
console.log(finalNumber4) // Output: "6"
Run Code Online (Sandbox Code Playgroud)
编辑
由于console.log部分似乎比评论中的链部分更有趣,我将添加确保控制台输出的方法是一个数字:
toString并使用字符串强制来获取对象的字符串表示形式toString完成链后不要忘记调用)valueOf并使用一元运算+符(这也将使您的类可用于二进制运算最后一个选项的代码:
class numbOp {
private n: number;
constructor(num: number) {
this.n = num;
}
public add(inc = 1) : this { // annotation not necessary added to address comments
this.n = this.n + inc;
return this;
}
valueOf() {
return this.n;
}
}
let finalNumber2 = new numbOp(3).add();
console.log(+finalNumber2) // Output: 4
console.log(1 + (+finalNumber2)) // Output: 5
console.log(1+(finalNumber2 as any as number)) // Output: 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
511 次 |
| 最近记录: |