// ts 객체지향 문법
// 생성자 생성하기(ㅋ)
class Player {
constructor(
private firstName:string,
private lastName: string,
public nickname:string
) {}
}
// this.뭐시깽이 = 뭐시깽이 하지말고 파라미터만 쓰면 알아서 생성해줌
/*
class Player {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.nickname = nickname;
}
}
컴파일된 모습
자바스크립트에는 private 옵션이 따로 존재하지 않음
타입스크립트는 private를 써서 사용자를 보호함
*/
const jaejun = new Player("jaejun", 'kim', 'kjjdsa')
jaejun.firstName //Property 'firstName' is private and only accessible within class 'Player'.
// private 기 때문에 사용할 수 없음
// 추상클래스(very very cooool!!)
// 다른클래스가 상속받을 수 있는, 즉 상속해주는 클래스.
// 인스턴스를 생성할 수 없음
abstract class Player_abstract {
constructor(
private firstName:string,
private lastName: string,
public nickname:string
) {}
private getFullname_private() { // private 메서드에도 쓸 수 있다. 근데 그럼 어케씀
return `${this.firstName} ${this.lastName}`
}
getFullname_public() {
return `${this.firstName} ${this.lastName}`
}
}
class Player_extends extends Player_abstract{
}
const jejun_ = new Player_abstract("jaejun", 'kim', 'kjjdsa') //Cannot create an instance of an abstract class.(2511)
const jejun = new Player_extends("jaejun", 'kim', 'kjjdsa')
jejun.getFullname_private() // Property 'getFullname_private' is private and only accessible within class 'Player_abstract'.
jejun.getFullname_public()
// 추상 메서드
// 추상 클래스를 만드는 이유는? 구현하고자 하는 무언가가 있을 것.
// 그 구현하고 싶은 대상을 미리 추상화해놓는 것 === 추상메서드
abstract class Player_abstract2 {
constructor(
private firstName:string,
private lastName: string,
private nickName:string,
protected nickName_protected:string
) {}
abstract getNickname(arg: string): void
// 문자열을 파라미터로 받고 void를 반환하는 getNickname 이라는 메서드를 꼭 만들어줘!
abstract getNickname2(arg: string): void
private getFullname_private() { // private 메서드에도 쓸 수 있다. 근데 그럼 어케씀
return `${this.firstName} ${this.lastName}`
}
getFullname_public() {
return `${this.firstName} ${this.lastName}`
}
}
class Player_extends2 extends Player_abstract2{
//Non-abstract class 'Player_extends2' does not implement inherited abstract member 'getNickname' from class 'Player_abstract2'.(2515)
// 아직 getNickname() 을 구현하지 않았다고 오류를 띄워줌!
getNickname2() {
console.log(this.nickName) // Property 'nickName' is private and only accessible within class
// nickName 분명히 있는데 접근안됨. 추상클래스 내에서 private 처리된 생성자는 외부도, 인스턴스(자식 클래스)도 접근할 수 없음
// 때문에 private 대신 protected 를 먹여주는게 자식클래스에서 쓸 수 있는 방법임
console.log(this.nickName_protected) // 쟈쟈쟌
}
}
/* 정리
타입스크립트는 this로 생성자를 지목할 필요가 없음. 파라미터를 써주면 알아서 생성자로 컴파일함
자바스크립트 클래스는 원래 private 기능이 없다.
타입스크립트는 private 기능이 있다.
때문에 생성자를 만들 때 세가지 옵션으로 공개, 일부공개, 비공개 하듯 생성자를 보호할 수 있다.
private: 생성자를 만든 부모클래스에서만 사용가능해짐
protected: 부모클래스와 자식클래스(인스턴스) 에서도 사용이 가능해짐
public: 달라는대로 다 줌
*/