클래스
- Javascript에서는 ES2015의 새로운 문법
- TypeScript에서의 클래스 기능은 C#에서 유래된 것이 많다.
- 일부 기능은 TS에서만 존재하는 고유 문법으로 컴파일 후에 사라진다.
class Person {
name : string;
age : number;
readonly location:string ='Korea'
}
const p = new Person();
생성자
class Person {
name : string;
age : number;
readonly location:string ='Korea'
constructor(name: string ,age: number){
this.name = name;
this.age = age;
}
}
const p1 = new Person('park',123);
const p2 = new Person('Poco',100);
console.log(p1);
console.log(p2);
메서드
class Person {
name : string;
age : number;
readonly location:string ='Korea'
constructor(name: string ,age: number){
this.name = name;
this.age = age;
}
introduce(): string{
return `${this.name}의 나이는 ${this.age}`
}
}
const p1 = new Person('park',123);
const p2 = new Person('Poco',100);
console.log(p1.introduce());
console.log(p2.introduce());
getter setter
class Person1 {
name: string;
private _age: number;
constructor(name: string, age: number){
this.name = name;
this._age = age;
}
get age(){
if(this._age === 0){
return'설정되지 않았습니다.'
}
return `나이는 ${this._age}세로 추정`
}
set age(age){
if(typeof age === 'number'){
this._age = age
}
this._age = 0
}
}
const p3 = new Person1('park',123);
console.log(p3.age);
console.log(p3.name);
- ts getter && setter 사용하는 과정에서 ECMA5이상에서만 지원한다는 에러 발견
💡 tsconfig.json에서 compilerOptions에다가 "target": "es5"을 추가해줌
extends
class 기본{
result(){
return 'Base'
}
}
class 파생 extends 기본{
result(): string {
return 'Derived'
}
}
const de = new 파생();
de.result()
super
- 기본 클래스 호출 시 사용
- 생성자에서 this 사용 전 호출 해야함
class Animal{
name :string
constructor(name:string){
this.name = name;
}
sayName(){
return`동물의 이름은${this.name}`
}
}
class Person3 extends Animal{
constructor(name: string){
super(name)
}
sayName(){
return `${super.sayName()}사람의 이름은${this.name}`
}
}
const person = new Person3('park');
접근 제어자
- 속성과 메서드에 접근을 제한할 수 있다.
- 클래스 내부 구현 정보를 적당히 공개하여 일부분만 노출시킨다.
- API와 비슷한 흉내를 낼 수 있다.
- 타입 시스템을 이용해 규칙을 강제할 수 있다.
제어자 | 설명 |
---|
public | 어디서나 접근가능(기본값) |
protected | 해당 클래스와 서브클래스에서만 접근 가능 |
private | 해당 클래스의 인스턴스에서만 접근 가능 |
class People{
public name: string
private age: number
protected gender:'M' | 'F'
constructor(name:string, age:number, gender:'M' | 'F'){
this.name= name
this.age =age
this.gender = gender
}
sayName(){
return `이름 ${this.name} 입니다`
}
protected sayAge(){
return `나이는 ${this.age}`
}
private sayGender(){
return ` 성별 타입은 ${this.gender}`
}
}
class Me extends People{
constructor(name:string, age:number, gender:'M' | 'F'){
super(name,age,gender)
}
sayInfo(){
return `${super.sayName()} ${super.sayAge()} `
}
}
const p = new People('park', 99 ,'M')
static
- 클래스의 속성과 메서드를 new로 인스턴스화 하지 않고 호출할 수 있다.
- 접근 제어자를 활용할 수 있다.
- 몇가지 정적 이름을 사용할 수 없다.
- 클래스는 그 자체로 new로 호출할 수 있는 함수이기 때문
class StaticClass{
private static type = 'type'
static getType(){
return StaticClass.type
}
}
StaticClass.getType()
readonly
- javascript에서는 사용할 수 없는 문법
class ReadOnlyClass{
name : string
readonly age : number
constructor(name:string,age:number){
this.name = name;
this.age = age
}
}
const r = new ReadOnlyClass('park', 99);
r.name = 'ppp'
r.age = 30;
추상 클래스
abstract
를 선언한 클래스로 직접 인스턴스화 될 수 없는 클래스
- 직접 인스턴스화 될 수 없지만
extends
후 파생된 클래스를 인스턴스화하도록 유도
- 추상 클래스는 구현된 메서드를 포함시킬 수 있다.
abstract
선언한 메서드는 파생된 클래스에서 메서드를 구현해야 함.
abstract class AnimalClass{
abstract hello() :string
run(){
return this.hello + 'run'
}
}
class AnimalC1 extends AnimalClass {
hello(){
return 'people'
}
}
class Dog extends Animal{
hello(){
return 'Dog'
}
}
const people = new AnimalC1()
parameter properties
class People1{
constructor(
public name:string,
private age:number,
protected gender:'M' | 'F'){
this.name= name
this.age =age
this.gender = gender
}
sayName(){
return `이름 ${this.name} 입니다`
}
protected sayAge(){
return `나이는 ${this.age}`
}
private sayGender(){
return ` 성별 타입은 ${this.gender}`
}
}
class Me1 extends People1{
constructor(name:string, age:number, gender:'M' | 'F'){
super(name,age,gender)
}
sayInfo(){
return `${super.sayName()} ${super.sayAge()} `
}
}
const pe = new People1('park', 99 ,'M')
메서드 오버라이딩
class Man{
run(){
return 'Animal이 달리다'
}
}
class Cat extends Man{
run(){
return 'Cat가 달리다'
}
}
class Woman extends Man{
run(){
return 'Woman이 달린다'
}
}
const w = new Woman();
const m = new Man();
const c = new Cat();
console.log(m.run());
console.log(c.run());
console.log(w.run());