TypeScript의 클래스에서 setter 메소드를 만드는 방법은 무엇입니까?
14127 단어 typescript
TypeScript의 class에서
setter 메서드를 만들려면 클래스에서 set 키워드 다음에 method definition을 사용할 수 있습니다.setter 메서드는 특정 클래스 필드의 값을 설정하는 데 사용됩니다. 대부분 값을 설정하기 전에 수행해야 할 처리가 있는 경우입니다.TL;DR
// a simple class
class Car {
_name: string;
yearMade: number;
constructor(name: string, yearMade: number) {
this._name = name;
this.yearMade = yearMade;
}
// setter method for the `name` class field
set name(name: string) {
this._name = name;
}
}
// create an instance of the `Car` class
const lexus = new Car("Lexus", 2022);
// cool part is that we can use
// `name` setter method like how we access a property
// note that we are not invoking the
// `name` even thought it's a "method" and
// just assigning a new value to the name property
// the new assigned value is then passed
// to the parameter in the setter method 👇🏽
lexus.name = "Lexus RX"; // ✅
// log the contents
console.log(lexus); // {_name: "Lexus RX", yearMade: 2022 } ✅
예를 들어 문자열 유형을 갖는
Car이라는 2 fields과 name 유형을 갖는 yearMade 및 number이라는 클래스가 있다고 가정하고 클래스의 필드 값을 다음과 같이 초기화합니다.// a simple class
class Car {
name: string;
yearMade: number;
constructor(name: string, yearMade: number) {
this.name = name;
this.yearMade = yearMade;
}
}
이제
name 클래스 필드에 대한 setter 메서드를 만들어 보겠습니다. 이를 위해 먼저 name 연산자를 사용하여 name 필드의 값을 설정하는 this이라는 매개변수가 있는 메서드를 생성하고 메서드에 키워드 set 접두사를 지정하는 것으로 시작할 수 있습니다. 예, 이것이 setter 메서드를 만들기 위해 해야 할 일의 전부입니다.다음과 같이 할 수 있습니다.
// a simple class
class Car {
name: string;
yearMade: number;
constructor(name: string, yearMade: number) {
this.name = name;
this.yearMade = yearMade;
}
// setter method for the `name` class field
set setName(name: string) {
this.name = name;
}
}
이제
Car 클래스의 인스턴스를 생성하고 어떻게 작동하는지 살펴보겠습니다.// a simple class
class Car {
name: string;
yearMade: number;
constructor(name: string, yearMade: number) {
this.name = name;
this.yearMade = yearMade;
}
// setter method for the `name` class field
set setName(name: string) {
this.name = name;
}
}
// create an instance of the `Car` class
const lexus = new Car("Lexus", 2022);
// cool part is that we can use
// `setName` setter method like how we access a property
// note that we are not invoking the
// `setName` even thought it's a "method" and
// just assigning a new value to the setName property
// the new assigned value is then passed
// to the parameter in the setter method 👇🏽
lexus.setName = "Lexus RX"; // ✅
위의 코드를 자세히 살펴보면 객체의 일반 속성에 액세스하고 메서드임에도 불구하고 호출하지 않는 것과 같이
setName을 사용하고 있음을 알 수 있습니다. 클래스의 모든 setter 메서드는 속성처럼 액세스됩니다.건설자 setter 메서드를 만들 때 주의해야 할 몇 가지 중요한 사항은 다음과 같습니다.
setter 메서드에는 매개변수가 하나만 있어야 합니다. setter 메서드가 값을 반환하지 않습니다. setter 메서드의 유일한 목적은 클래스 필드에 일부 값을 설정하는 것입니다. setter 메서드는 개체의 속성처럼 액세스할 수 있으며 setter 메서드에 할당된 모든 값은 = 연산자(할당 연산자)를 사용하여 수행되며 이 값은 setter 메서드의 매개 변수로 전달됩니다. 네, 이것이 제가 말한 놀라운 일입니다. 쿨 맞아요🤩!
이제
setter 필드에 대해 name 메서드를 만드는 번거로움을 감수해야 하는 이유가 무엇인지 생각할 수 있습니다. 클래스 인스턴스에서 name 필드에 간단히 액세스할 수 있습니다.하지만
private 필드라면 그렇게 할 수 없습니다. 다가오는 블로그에서 private 클래스 필드에 대해 더 자세히 논의할 것입니다.주요한 큰 이유는 필드 자체에 대한 값을 설정하기 전에 일부 논리를 실행하거나 일부 처리를 수행하는 것입니다.
이제 이름을 지정하기 위해
name 필드의 이름을 _name으로 바꾸고 setName setter 메서드의 이름을 개체의 속성으로 액세스하므로 name으로 바꾸겠습니다. 이러한 규칙을 따르는 것이 가장 좋습니다.이렇게 할 수 있습니다.
// a simple class
class Car {
_name: string;
yearMade: number;
constructor(name: string, yearMade: number) {
this._name = name;
this.yearMade = yearMade;
}
// setter method for the `name` class field
set name(name: string) {
this._name = name;
}
}
// create an instance of the `Car` class
const lexus = new Car("Lexus", 2022);
// cool part is that we can use
// `name` setter method like how we access a property
// note that we are not invoking the
// `name` even thought it's a "method" and
// just assigning a new value to the name property 👇🏽
// the new assigned value is then passed
// to the parameter in the setter method 👇🏽
lexus.name = "Lexus RX"; // ✅
// log the contents
console.log(lexus); // {_name: "Lexus RX", yearMade: 2022 } ✅
TypeScript에서 클래스 필드에 대한
setter 메서드를 성공적으로 생성했습니다. 예이 🥳!위의 코드는 에 있습니다.
그게 다야 😃!
코드샌드박스 이 정보가 유용하다고 생각되면 자유롭게 공유하세요 😃.
Reference
이 문제에 관하여(TypeScript의 클래스에서 setter 메소드를 만드는 방법은 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/melvin2016/how-to-make-a-setter-method-in-a-class-in-typescript-4k1d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)