0

我想对私有变量执行简单的 get/set 方法,所以我这样做了

_Var1:number = 0;

Var1():number
{
   return this._Var1;
}

Var1(num:number)
{
   this._Var1 = num;
}

这会引发编译器错误。一个不带参数的方法和一个带一个参数的方法可以共享相同的名称吗?

4

3 回答 3

4

Here you go

    Var1(input?:number):number
    {
        if(typeof input != typeof 123)
            return this._Var1;
        else
            return this._Var1 = input;
    }

However if you are curious about the overload signatures, you would need to do something like this:

class Foo{

    _Var1:number = 0;

    // Sample of overload signatures
    Var1():number
    Var1(input:number):number
    Var1(input?:any):number // The last signature Must be super set of all previous signatures. 
    {
        if(typeof input != typeof 123)
            return this._Var1;
        else
            return this._Var1 = input;
    }
}

More

Docs on function overloading : https://basarat.gitbooks.io/typescript/content/docs/types/functions.html#overloading

于 2013-08-11T05:46:54.520 回答
1

If you are targeting ECMAScript 5 or above, your code just needs the get and set keywords:

_Var1:number = 0;

get Var1():number
{
   return this._Var1;
}

set Var1(num:number)
{
    this._Var1 = num;
}

If you want to target older version, I would recommend using getVar1 and setVar1 method names rather than an overload, which would force you to check the input. The two methods are very concise.

Alternatively, you can take advantage of a neat trick that allows you to use runtime variables as default arguments:

Var1(num: number = this._Var1) {
    return this._Var1 = num;
}

I still prefer methods named get... and set... for the following reasons: the generated JavaScript for this will look heinous because it will contain code that is unnecessary for gets. It also returns a value when you set, which isn't the normal convention.

于 2013-08-11T07:29:12.347 回答
1

您需要函数重载的通用实现:

Var1(): number;
Var1(num: number): void;
Var1(num?: number): any
{
    if (num === undefined) return this._Var1;
    this._Var1 = num;
}

重载的是函数的声明,而不是它的实现。最后一行:Var1(num?: number): any是泛型函数声明。有必要。它上面的行是重载的声明。

于 2013-08-13T03:40:27.673 回答