→ 이 셋을 통칭하여 멤버(member)라 부른다.
class Person {
name : string;
constructor(name : string) {
this.name = name;
}
say() {
return "Hello, My name is" + this.name
}
}
let person = new Person("june");
this.
"를 앞에 붙이면 클래스의 멤버임을 의미*인스턴스(instance) : new 연산자에 의해 생성된 객체
- public
class Animal {
public name: string
constructor(theName: string){
this.name = theName;
}
}
new Animal("Cat").name
- protected
class Person{
protected name: string
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
private department: string
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // Error
// 외부 객체에서 직접적으로 protected 타입의 name을 선언하여 Error 발생
- private
class Animal {
private name: string
constructor(theName: string){
this.name = theName;
}
}
new Animal("Cat").name // Error
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color}`);
}
getArea() {
return width * this.height;
}
}
class Rectangle extends Shape{}
class Triangle extends Shape{
draw(){ // overriding !!!
super.draw(); // 부모의 draw() 메소드도 상속 받겠다!
console.log('🔺');
}
getArea() { // overrding !!!
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, 'red');
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age; // callstack의 무한 반복을 방지하기 위해 getter & setter 변수 이름을 다르게 (관례적으로 '_'를 추가) 한다.
}
set age() {
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User("Steve", "Job", -1);
console.log(user1.age) // 0
클래스명.
"을 앞에 붙여 static 멤버에 접근 가능class Article {
static publisher = 'Dream Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.publisher); // Error
console.log(Article.publisher); // Dream Coding
Article.printPublisher(); // Dream Coding
abstract class Animal {
protected name: string
constructor(name: string){
this.name = name;
}
abstract makeSound(): void
move(): void {
console.log('move!!");
}
}
class Dog extends Animal {
constructor(name: string) {
super(name: string) {
super(name); // 파생된 클래스의 생성자는 반드시 super() 호출
}
makeSound(): void {
console.log(this.name + " 멍멍!!");
}
}
const animal = new Animal('animal');
// Error → 추상 클래스를 직접 사용 불가
const dog = new Dog("진돗개");
dog.makeSound(); // 진돗개 멍멍!!
출처 - [엘리스 강의 자료], [드림코딩]