Class란 정보를 묶는 도구라고 생각하면 좋고
쉽게 빵틀이라고 생각하면 된다. 그 틀에 만들어지 빵들을 객체라고 하면 되는거고 빵하나하나를 변수라고 생각하면 된다.
그렇기에 클래스를 이용한 객체를 우리는 인스턴스라고 한다.
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
이처럼 우리는 클라스 user라는 빵 전체 틀에 user을 구울 수 있다.
또한 이런 빵 하나하나 굽는 틀을 생성자로 정의할 수 있는데
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
이처럼 this을 사용해서 user라는 빵 전체 틀에 constructor라는 빵틀을 만들어 this라는 연산자로 함수를 지정해주면
이렇게 뒤에는 이름, 나이, 기술 순서대로 new user을 정의해주기만해도
생성자를 이용한 빵틀로 구워진 빵들인 객체가 생성된다.
그 객체는 this라는 연산자로 생성자의 객체값이 되는것이다. 참쉽죠?
또한 매서드란 프로퍼티 값이 함수 일 경우 일반함수와 구별하기 위해 사용되는데 class라는 object에 묶여있는 함수를 우리는 매서드라고 한다.
class User {
constructor(name, age, tech) { // User 클래스의 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
getName() { return this.name; } // getName 메서드
getAge() { return this.age; }. // getAge 메서드
getTech() { return this.tech; } // getTech 메서드
}
const user = new User("이용우", "28", "Node.js"); // user 인스턴스 생성
console.log(user.getName()); // 이용우
console.log(user.getAge()); // 28
console.log(user.getTech()); // Node.js
상속이란 부모의 클래스를 자식에게 할당하는 것으로 예시를 보며 설명해보자
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
이처럼 부모인 user 클래스가 있거 이레 employee는 user라는 클래스의 생성자를 할당 박아 쓰려고한다.
그렇기에 extends을 이용하여 employee extends user로 고용자는 유저의 자식클래스이다라는 의미이며
자식클래스의 생성자에 변수를 할당하면 부모클래스의 생성자를 따라서 메서드로 테크닉이 호출된다.
다시한번, 이렇게 할당되는 변수가 함수일 때를 대비하여 우리는 매소드 방법을 쓸수 있고 그 함수 또한 자식함수에 똑같이 유전되어 할당된다.