846

プロパティのgetメソッドとsetメソッドを作成しようとしています。

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

値を設定するためのキーワードは何ですか?

4

11 に答える 11

1348

TypeScriptは、ECMAScript4/ActionScript3のようなgetter/setter構文を使用します。

class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

これにより、ECMAScript5機能を使用してこのJavaScriptが生成されObject.defineProperty()ます。

var foo = (function () {
    function foo() {
        this._bar = false;
    }
    Object.defineProperty(foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (value) {
            this._bar = value;
        },
        enumerable: true,
        configurable: true
    });
    return foo;
})();

だからそれを使うには、

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

ただし、これを使用するには、TypeScriptコンパイラがECMAScript5をターゲットにしていることを確認する必要があります。コマンドラインコンパイラを実行している場合は、次の--targetようなフラグを使用します。

tsc --target ES5

Visual Studioを使用している場合は、プロジェクトファイルを編集して、TypeScriptCompileビルドツールの構成にフラグを追加する必要があります。あなたはここでそれを見ることができます:

@DanFromGermanyが以下に示唆しているように、のようなローカルプロパティを単に読み書きしている場合foo.bar = true、セッターとゲッターのペアを持つのはやり過ぎです。プロパティの読み取りまたは書き込みが行われるたびに、ロギングなどの処理が必要になった場合は、いつでも後で追加できます。

ゲッターは、読み取り専用プロパティを実装するために使用できます。これは、ゲッターが読み取り専用およびオプションの型とどのように相互作用するかも示す例です。

//
// type with optional readonly property.
// baz?:string is the same as baz:string|undefined
//
type Foo = {
    readonly bar: string;
    readonly baz?: string;
}
const foo:Foo = {bar: "bar"}
console.log(foo.bar) // prints 'bar'
console.log(foo.baz) // prints undefined

//
// interface with optional readonly property
//
interface iFoo {
    readonly bar: string;
    readonly baz?: string;
}

const ifoo:iFoo = {bar: "bar"}
console.log(ifoo.bar)  // prints 'bar'
console.log(ifoo.baz)  // prints undefined


//
// class implements bar as a getter, 
// but leaves off baz.
//
class iBarClass implements iFoo {

    get bar() { return "bar" }
}
const iBarInstance = new iBarClass()
console.log(iBarInstance.bar) // prints 'bar'
console.log(iBarInstance.baz) // prints 'undefined'
// accessing baz gives warning that baz does not exist 
// on iBarClass but returns undefined
// note that you could define baz as a getter
// and just return undefined to remove the warning.


//
// class implements optional readonly property as a getter
//
class iBazClass extends iBarClass {
    private readonly _baz?: string

    constructor(baz?:string) {
        super()
        this._baz = baz
    }

    get baz() { return this._baz; }
}

const iBazInstance = new iBazClass("baz")
console.log(iBazInstance.bar)  // prints bar
console.log(iBazInstance.baz)  // prints baz
于 2012-10-12T00:19:25.973 に答える
147

Ezward はすでに適切な回答を提供していますが、コメントの 1 つに使用方法が尋ねられていることに気付きました。この質問に出くわした私のような人々にとって、Typescript Web サイトのゲッターとセッターに関する公式ドキュメントへのリンクがあると便利だと思いました。使用例を示します。

http://www.typescriptlang.org/docs/handbook/classes.html

特に、それに慣れていない人のために、「get」という単語をゲッターへの呼び出しに組み込まないことに注意してください (セッターの場合も同様です)。

var myBar = myFoo.getBar(); // wrong    
var myBar = myFoo.get('bar');  // wrong

これを行うだけです:

var myBar = myFoo.bar;  // correct (get)
myFoo.bar = true;  // correct (set) (false is correct too obviously!)

次のようなクラスが与えられます:

class foo {
  private _bar:boolean = false;

  get bar():boolean {
    return this._bar;
  }
  set bar(theBar:boolean) {
    this._bar = theBar;
  }
}

次に、プライベート '_bar' プロパティの 'bar' ゲッターが呼び出されます。

于 2016-01-15T12:53:30.823 に答える
68

正しい方向を示す実際の例を次に示します。

class Foo {
    _name;

    get Name() {
        return this._name;
    }

    set Name(val) {
        this._name = val;
    }
}

JavaScript のゲッターとセッターは、単なる通常の関数です。セッターは、値が設定される値であるパラメーターを取る関数です。

于 2012-10-10T20:07:27.307 に答える
4

あなたが示す例に基づいて、データオブジェクトを渡し、そのオブジェクトのプロパティをget()で取得したいと考えています。このためには、ジェネリック型を使用する必要があります。データ オブジェクトはジェネリックであるため、任意のオブジェクトにすることができます。

export class Attributes<T> {
    constructor(private data: T) {}
    get = <K extends keyof T>(key: K): T[K] => {
      return this.data[key];
    };
    set = (update: T): void => {
      //   this is like spread operator. it will take this.data obj and will overwrite with the update obj
      // ins tsconfig.json change target to Es6 to be able to use Object.assign()
      Object.assign(this.data, update);
    };
    getAll(): T {
      return this.data;
    }
  }

< T > はジェネリック型を指します。インスタンスを初期化しましょう

 const myAttributes=new Attributes({name:"something",age:32})

 myAttributes.get("name")="something"

この構文に注意してください

<K extends keyof T>

これを使用するには、次の 2 つの点に注意する必要があります。

1- in typestring 文字列は型にすることができます。

2- JavaScript のすべてのオブジェクト プロパティは基本的に文字列です。

get() を使用する場合、受け取る引数の型は、コンストラクターに渡されたオブジェクトのプロパティです。オブジェクトのプロパティは文字列であり、文字列は typescript の型として許可されているため、これを使用できます。 <K extends keyof T>

于 2020-10-28T18:37:10.913 に答える
2

これは一般的なメソッドを作成するのと非常によく似ており、キーワードを予約済みgetまたはset先頭に置くだけです。

class Name{
    private _name: string;

    getMethod(): string{
        return this._name;
    }

    setMethod(value: string){
        this._name = value
    }

    get getMethod1(): string{
        return this._name;
    }

    set setMethod1(value: string){
        this._name = value
    }
}

class HelloWorld {

    public static main(){

        let test = new Name();

        test.setMethod('test.getMethod() --- need ()');
            console.log(test.getMethod());

        test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';
            console.log(test.getMethod1);
    }
}
HelloWorld.main();

この場合、戻り値の型をスキップできますget getMethod1() {

    get getMethod1() {
        return this._name;
    }
于 2016-03-22T14:13:03.823 に答える
2

以下は、ゲッターとセッターを追加する方法の例です-

class Person {
    private _age: number;
    private _firstName: string;
    private _lastName: string;

 
    public get age() {
        return this._age;
    }

    public set age(theAge: number) {
        if (theAge <= 0 || theAge >= 200) {
            throw new Error('The age is invalid');
        }
        this._age = theAge;
    }

    public getFullName(): string {
        return `${this._firstName} ${this._lastName}`;
    }
}
于 2021-09-03T09:25:07.487 に答える