Оглавление:
Карта сайта:
Оглавление:
Карта сайта:
Это старая версия документа!
Ниже показан простой класс 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 метод начинается с ключевого слова 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}`; } }
Как это работает.
Теперь вы можете получить доступ к методу определения возраста следующим образом:
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}`; } }
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.
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);