JS 는 데이터 타입을 크게 원시 & 객체 타입으로 분류된다
리터럴 -> 사람이 이해할 수 있는 문자 또는 약속된 기호를 사용해 값을 생성하는 표기법
=> ~객체 리터럴은 객체를 생성하기 위한 표기법 이다~
객체 리터럴은 {} 안에 0개의 프로퍼티를 정의해서 선언한다
( 즉 프로퍼티가 0개여도 선언이 가능하다 )
객체의 상태를 나타내는 값 ( DATA ) 이다
Key : value 로 구성되어 있다
객체에서 프로퍼티의 값이 함수로 구성되어 있는 경우이다
현실과 비슷한 개념(객체)를 나타내기 위한 도구를 클래스 라고 한다
클래스를 미리 정의해 놓고 필요할 때마다 해당 클래스로 동일한 틀을 가진 객체를 생성해 사용할 수 있으며
클래스를 통해 생성한 객체를 ~인스턴스 (instance)~ 라고 한다
class User {
}
const user = new User();
user.name = "이용우";
user.age = 28;
user.tech = "Node.js";
console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js
클래스 내부에서 constructor() 로 정의한 메서드를 "생성자" 라고 한다
class User {
constructor(name, age, tech) { // User 클래스의 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
}
const user = new User("이용우", 28, "Node.js"); // user 인스턴스 생성
console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js
class 안에 constructor 에 있는 순서대로
new User() 의 매개변수가 들어가서
이용우가 user.name 에;
28 이 user.age 에;
Node.js 가 user.tech 에 들어가게 된다
% 여기서 this 는 클래스를 사용해 만들어 질 객체 그 자신을 의미한다
일반적으로 클래스의 인스턴스는 선언한 클래스의 기능을 모두 상속한다
부모 클래스의 경우 메서드 내부변수와 같은 정보를 자식 클래스에게 할당해줄 수 있다
class User { // User 부모 클래스
constructor(name, age, tech) { // 부모 클래스 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
getTech(){ return this.tech; } // 부모 클래스 getTech 메서드
}
class Employee extends User{ // Employee 자식 클래스
constructor(name, age, tech) { // 자식 클래스 생성자
super(name, age, tech);
}
}
const employee = new Employee("이용우", "28", "Node.js");
console.log(employee.name); // 이용우
console.log(employee.age); // 28
console.log(employee.getTech()); // 부모 클래스의 getTech 메서드 호출: Node.js
여기서 class Employee 는 class User 를 상속하고 있다
따로 this.name 등을 설정해주지 않고 super 를 통해 부모를 따라갈 수 있다
이때 자식 class 인 employee 는 부모의 메서드까지 상속받아
getTech 메서드를 employee 에서도 사용할 수 있