객체와 클래스
객체 지향 프로그래밍이란?
객체 → 상태를 나타내는 '변수', 행동을 나타내는 '함수'
절자치향 프로그래밍 → 순서대로 그냥 짜는거
변수와 함수를 하나로 묶는 객체란 개념이 등장함.
Object - Literal
const user = {
email : 'koallarry11@kaist.ac.kr',
birthdate: '1992-03-21',
buy(item){
console.log('${this.email} buys ${item.name}');
}
Factory function
수십 수백개의 객체를 생성하려면 코드 양이 엄청 많아진다.
function createUser(email,birthdate){
const user = {
email: email,
birthdate: birthdate,
buy(item){
console.log('${this.email} buys ${item.name}'_;
},
};
return user;
}
const user1 = createUser('crhis123@gmail.com', '1992-03-21');
const user2 = createUser('~~~~', '~~~~');
생성자랑 똑같네...
프로퍼티와 파라미터의 이름이 같으면 생략가능하다
즉
function createUser(email,birthdate){
const user = {
email,
birthdate,
buy(item){
console.log('${this.email} buys ${item.name}'_;
},
};
return user;
}
constructor function
생성자 함수
functinoi User(email,birthdate){
this.email = email;
this.birthdate = birthdate;
this.buy = function (item){
console.log('${this.email} buys ${item.name}'};
};
}
const user1 = new User('chris123@google.com','1992-03-21');
JavaScript
복사
class키워드
class User{
construct(email, birthdate){
this.email = email;
this,birthdate = birthdate;
}
buy(item){
console.log('${this.email} buys ${item.name}');
}
}
const user1 = new User('chris123@google.com','1992-03-01');
JavaScript
복사
객체 지향 프로그래밍의 4개의 기둥
추상화, 캡슐화 , 상속, 다형성
추상화 : 어떤 구체적인 존재를 원하는 방향으로 간략하게 설계하는 것
캡슐화: 객체의 특정 프로퍼티에 직접 접근하지 못하도록 막는것
class User{
construct(email, birthdate){
this.email = email;
this,birthdate = birthdate;
}
buy(item){
console.log('${this.email} buys ${item.name}');
}
get email(){
return this._email;
} // email이라는 프로퍼티 값이 실제로 읽히지 않는다.
set email(address){
//setter메소드
//검증하고 프로퍼티에 대입하기
if(address.include('@')){
this._email = address;
//새롭게 설정한 프로퍼티, 숨기고 싶은 프로퍼티 _email
//email 은 그냥 함수 이름일 뿐
}else{
throw new Error('invalid email address');
}
}
}
const user1 = new User('chris123@google.com','1992-03-01');
user1.email = 'chris rober'; -> email이라는 함수가 실행된다.
JavaScript
복사
상속
class PremiumUser extends User{
}
User클래스에 있는 프로퍼티와 메소드를 물려받는다.
베이스가 되는 클래스 = 부모 클래스
상속 받는 클래스 = 자식 클래스
겹치는 부분을 제외하고 다른 부분만 적으면 된다.
super Constructor ( 슈퍼 생성자 )
⇒ 자식 클래스로 객체를 만드려고 할 때는 생성자 안에서 super()함수를 호출해서 부모 생성자를 생성해야한다.
super()의 파라미터에는 부모 클래스에서 필요한 파라미터를 넘겨줘야한다.
다형성
많은 형태를 갖고 있는 성질
오버라이딩 → 덮어쓰다. 부모 클래스의 메소드를 덮어쓰는 것
같은 함수를 재정의하면 덮어쓰는 것처럼 행동한다.
부모 클래스의 메소드가 필요하다면 → super.buy(item)처럼 쓰면 된다.
instance of
users.forEach((user)⇒{
console.log(user instanceof PremiumUser);
});
PremiumUser 클래스의 객체인지 아닌지 확인해주는 것
자식 클래스로 만든 객체는 부모클래스로 만든 객체로도 인정된다.
static 프로퍼티와 static 메소드
클래스에 직접적으로 딸려있는 프로퍼티와 메소드
객체가 아닌 클래스 자체로 접근하고 싶은 것
수학 계산에 필요한 함수와 변수