Class전통적인 객체지향과는 조금 다르다.
Class 정의 - 프로토타입을 쉽게 사용하기 위한 Sugar Syntax(설탕 문법)// 기존 생성자 함수
function PersonF(name, age) {
this.name = name;
this.age = age;
}
const personF = new PersonF("철수", 20);
console.log(personF); //PersonF { name: '철수', age: 20 }
// class 사용
class PersonC {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const personC = new Person("빌리", 20);
console.log(personC); // PersonC { name: '빌리', age: 20 }
Class의 메서드는 무조건 프로토타입으로 들어가 있다.
function PersonF(name, age) {
this.name = name;
this.age = age;
}
PersonF.prototype.getInfo = function () {
console.log(`${this.name} ${this.age}`);
};
const personF = new PersonF("철수", 20);
personF.getInfo();
console.log(personF);
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
console.log(`${this.name} ${this.age}`);
}
}
const personC = new Person("빌리", 20);
personC.getInfo();
console.log(personC);
객체는 아니지만 객체로 취급이 되는 특징, 특성, 것
특정 데이터가 객체로 취급되는 것
함수는 함수라는 데이터. 그러나, 자바스크립트에서는 객체로 취급
일급객체 → 함수, class
일급 객체의 조건
변수에 할당이 가능해야함
const sum = function(){}
함수의 인자로 전달할 수 있어야함
function a(callback){
callback()
}
function greet(){
console.log("hello~!")
}
a(greet) // hello~!
함수의 반환 값으로 사용할 수 있어야 함
function outer(){
return function (){
console.log("inner")
}
}
const a = outer();
a();
동적으로 생성이 가능해야함
const dynamicFunc = new Function('name',"return '안녕하세요. ' + name");
dynamicFunc('동원)
prototype 상속생성자 함수보다 간단한 프로토타입 상속
class Car {
constructor(name) {
this.name = name;
}
getInfo() {
console.log(`${this.name} `);
}
}
class Benz extends Car { // extends로 Car라는 Class를 상속
constructor(name, color) {
super(name); // super()로 데이터 프로퍼티를 Car에 넘겨줌
this.color = color;
}
getColor() {
console.log(`${this.color} `);
}
}
const benz = new Benz("붕붕이", "blue");
benz.getInfo();
⚠️ class문법은 상속 시 상속받는 새로운 class에 super() 를 넣어줘야 한다.
인스턴스를 생성하지 않고 사용할 수 있는 메서드 static
class MathUtils {
static add(n1, n2) {
return n1 + n2;
}
}
// const math = new MathUtils();
const sum = MathUtils.add(10, 20);
console.log(sum);
멤버속성을 만들지 않고 해당 속성으로 다이렉트로 할당 되기 때문에 메모리적 이점
⚠️ 인스턴스로는 호출 할 수 없다.
인스턴스 객체의 속성 값을 바꿀 때, 바꾸는 것을 제어하고 싶은 경우 get, set
class Car {
constructor(speed) {
this._speed = speed;
}
set speed(value) {
this._speed = value < 0 ? 0 : value;
}
get speed() {
return this._speed;
}
}
const car = new Car(200);
car.speed = -100;
console.log(car.speed);
멤버 속성을 다루는 로직 추가 가능
class Counter {
constructor(count) {
this.count = count;
}
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
const count = new Counter(0);
count.increment(); // 1
count.increment(); // 2
count.count = 200;
console.log(count.count); // 200
자바스크립트에서 객체는 이렇게 동적으로 수정 당할 수 있다. 이걸 막는 것이 프라이빗 필드
class Counter {
#count = 0;
constructor(count) {
this.#count = count;
}
increment() {
this.#count++;
}
decrement() {
this.#count--;
}
getCount() {
return this.#count;
}
}
const count = new Counter(0);
count.increment(); // 1
count.increment(); // 2
count.count = 200;
console.log(count.getCount()); // 2
#을 붙여 간단하게 설정할 수 있다.
count["#count"] = 200;