Инструменты пользователя

Инструменты сайта


typescript:oop:getters_and_setters

Это старая версия документа!


TypeScript Getters и Setters

вступление в TypeScript Getters и Setters

Ниже показан простой класс Person с тремя свойствами: age, firstName, and lastName:

class Person {
    public age: number;
    public firstName: string;
    public lastName: string;
}

Чтобы получить доступ к любому свойству класса Person, вы можете просто поступить следующим образом:

let person = new Person();
person.age = 26;

Предположим, что вы присваиваете свойству age значение, полученное из пользовательского ввода:

person.age = inputAge;

Вводимое значение может быть любым числом. Чтобы убедиться в достоверности возраста, вы можете провести проверку перед назначением следующим образом:

if( inputAge > 0 && inputAge < 200 ) {
    person.age = inputAge;
}

Использование этой проверки во всех местах является избыточным и утомительным.

Чтобы избежать повторения проверки, вы можете использовать setters и getters. getters и setters позволяют вам контролировать доступ к свойствам класса.

Для каждого свойства:

  • getter метод возвращает значение значения свойства. Средство получения также называется средством доступа.
  • setter метод обновляет значение свойства. Сеттер также известен как мутатор.

getter метод начинается с ключевого слова get, а метод setter начинается с ключевого слова set.

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}`;
    }
}

Как это работает.

  • First, Сначала измените модификаторы доступа свойств age, FirstName и LastName с public на private.
  • Во-вторых, измените свойство age на _age.
  • В-третьих, создайте методы getter и setter для свойства _age. В методе setter проверьте достоверность введенного возраста, прежде чем присваивать его свойству _age.

Теперь вы можете получить доступ к методу определения возраста следующим образом:

let person = new Person();
person.age = 10;

Notice that the call to the setter doesn’t have parentheses like a regular method. When you call person.age, the age setter method is invoked. If you assign an invalid age value, the setter will throw an error:

person.age = 0;

Error:

Error: The age is invalid

When you access the person.age, the age getter is invoked.

console.log(person.age);

The following adds the getters and setters to the firstName and lastName properties.

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 get firstName() {
        return this._firstName;
    }
 
    public set firstName(theFirstName: string) {
        if (!theFirstName) {
            throw new Error('Invalid first name.');
        }
        this._firstName = theFirstName;
    }
 
    public get lastName() {
        return this._lastName;
    }
 
    public set lastName(theLastName: string) {
        if (!theLastName) {
            throw new Error('Invalid last name.');
        }
        this._lastName = theLastName;
    }
 
    public getFullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }
}

More TypeScript Getters/Setters Examples

As you can see from the code, the setters are useful when you want to validate the data before assigning it to the properties. In addition, you can perform complex logic.

The following shows how to create the fullname getter and setter.

class Person {
    // ... other code 
    public get fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
 
    public set fullName(name: string) {
        let parts = name.split(' ');
        if (parts.length != 2) {
            throw new Error('Invalid name format: first last');
        }
        this.firstName = parts[0];
        this.lastName = parts[1];
    }
}

How it works.

  • The getter method returns the concatenation of the first name and last name.
  • The setter method accepts a string as the full name with the format: first last and assign the first part to the first name property and second part to the last name property.

Now, you can access the fullname setter and getter like a regular class property:

 let person = new Person();
 person.fullname = 'John Doe';
 
 console.log(person.fullName);
typescript/oop/getters_and_setters.1676227963.txt.gz · Последние изменения: 2023/02/12 21:52 — werwolf