OOP Class

mandarinduk·2021년 3월 19일
0

class lever & instance(object) lever

class lever

변하지 않는 상수 값은 static을 붙여서 class 변수로 선언
class 변수로 선언하지 않으면 인스턴스가 생성될 때마다 중복으로 데이터가 생성되기 때문에 메모리 낭비 발생!

static MONTH:number = 12;

함수도 class lever로 선언 가능
함수를 static으로 선언하면 새로운 인스턴스를 사용하지 않고도 해당 함수를 className.method() 사용 가능!(ex. Math.round())

instance 변수를 사용할 때는 this를 붙이고, class 변수는 class name을 앞에 붙여서 사용

class Student {
	static MONTH:number = 12;
	name:string = "bae";

	// Student.MONTH
	// this.name
}

public, private, protected

public

default 값


private

외부에서 접근 불가

public을 사용하면 외부에서 설정 값을 잘못 설정할 수도 있음(제약 사항이 없음)
private 키워드를 사용하여 외부에서 조작 못하도록 설정, 해당 값을 설정할 수 있는 함수를 생성

class Student {
	static MONTH:number = 12;
	private name:string = "bae";

	// Student.MONTH
	// this.name

	constructor() {}

	changeName(name) {
    	if (!name) {
          throw new Error('이름을 입력하세요')
        }
      	this.name = name;
    }
      
}

const student = new Student();
student.name = "kim" // private 키워드이기 때문에 외부에서 접근하여 변경 불가능
student.changeName("kim") // 정의된 메서드를 활용하여 name 변경

constructor를 private로 선언, 함수를 활용하여 인스턴스를 만들도록 강요

class Student {
	static MONTH:number = 12;
	name:string = "bae";

	// Student.MONTH
	// this.name

	private constructor() {}
	static makeInstance() {
    	return new Student();
    }

	// constructor로 인스턴스 생성 불가
	// Student.makeInstance로 인스턴스를 생성하도록 강요
}

protected

부모 class를 상속 받은 자식 class에서만 접근 가능

profile
front-end 신입 개발자

0개의 댓글

관련 채용 정보