Typescript 익히기 (class / extends)

devtaco·2020년 5월 20일
0

Front-End(1.Typescript)

목록 보기
5/7
post-thumbnail

12.class_.ts

class

typescript 에서도 클래스 사용이 가능합니다.
es5 가 es6 로 버전업 되면서 typescript에도 class 개념이 도입되었습니다.

그럼 자바에서의 클래스와 다른점은 무엇일까요

자바와 다른점
1. 자바에서는 생성자 > 클래스이름과 동일하게 사용한다.
typescript 에서의 생성자는 constructor() 라는 method를 이용합니다.

  1. 멤버변수를 선언 > 생성자에게 매개변수를 전달해서 저장(동적으로)

사용해봅시다

class person_{ // person_이라는 클래스 선언
  name	// 멤버변수로 name과age를 갖습니다.
  age
  constructor(name,age){ // 이 부분이 생성자입니다. 생성자가 클래스이름이 아니죠?
      this.name = name; // 동적으로 들어감
      this.age = age;
  }
}

class person2_{ // person2_클래스
  address; 
  constructor(public name:string, public age:number){}
  //constructor(){} // 얘는 매개변수가 없는 생성자인데, 이미 매개변수가 있는 생성자를 선언해 놔서 중복이 불가능합니다.
}

위의 코드는 설계를 위한 클래스만 선언했기 때문에 결과화면이 없습니다.

13.classextend_.ts

extends

클래스를 만들 수 있다면, 상속 도 가능합니다.
(JAVA를 다룰 줄 아신다는 가정이 있습니다. )

사용해봅시다

class Animal_{  // 동물이라는 클래스를 먼저 생성합니다.
  weight_:any; // 속성명 : 자료형(string,number) > any (뭐든지 가능하다는 표시입니다.)
  
  constructor(weight_){ // 생성자입니다. weight_이라는 매개변수를 받습니다.
      this.weight_ = weight;
  }
  weight(){ // this.멤버변수(=속성명) 해당 클래스인스턴스의 값을 표시하는 method 입니다. 	
      console.log(this.weight_); 
  }
  eat(){
      console.log('Animal Eat!')
  }
}

class Human_ extends Animal_{ // 인간은 동물의 한 갈래니까 상속을 받아봅니다.
  language_ : string;
  //weight_:any; 이것은 기본적으로 부모인 Animal이 갖고있는 속성입니다.
  constructor(weight,language){
      super(weight); // 부모클래스의 생성자로 우선 초기화를 합니다.
      this.language_ = language;
  }
  
  //오버라이딩 부분입니다. Animal에 선언된 메소드를 수정합니다.
  eat(){
      console.log('Human Eat!');
  }
  speak(){
      console.log(`koreans speak ${this.language_}`);
  }
}

자바에서는 클래스명 객체명 = new 생성자(값,값2);

es6(typescript)에서는 객체명 = new 생성자(값,값2);

const korean_ = new Human_(66, 'Korean'); //korean_이 객체죠?
korean_.weight();
korean_.eat();
korean_.speak();

형식) 객체명 instanceof 클래스명 = true or false
: 이 객체가 해당 클래스의 인스턴스인지 확인해주는 기능입니다.

// 객체명 instacneOf 클래스명 = true or false 이게 이 클래스의 객체인지 아닌지 
console.log(korean_ instanceof Human_); //true
console.log(korean_ instanceof Animal_); //true

profile
웹프로그래밍 공부를 시작한 패션디자이너 출신 웹린이

0개의 댓글

관련 채용 정보