일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- react
- props와 state 차이점
- 자바스크립트
- CSS
- MPA
- undeclared
- 변수 생성 단계
- 서버 사이드 렌더링
- 브라우저 렌더링원리
- 로컬 스토리지
- 세션 스토리지
- 리액트
- 자바스크립트 함수
- 프로미스
- 호이스팅
- 깊은 복사
- webpack
- 실행 컨텍스트
- async/await
- 주소창에 naver 입력시 일어나는 일
- 리액트의 생명 주기
- 클라이언트 사이드 렌더링
- 얕은 복사
- polyfill
- 스코프 체인
- CORS
- 가상 dom
- 이벤트 캡처링
- 자바스크립트의 클래스
- 이벤트 버블링
Archives
- Today
- Total
Gapus Dev Blog
[자바스크립트] 클래스에 대해 본문
클래스(Class)
설명
- 객체 지향 프로그래밍에서 사용되는 개념
- 객체를 생성하기 위한 템플릿
- 클래스를 사용하면 비슷한 속성과 메서드를 가진 객체를 쉽게 생성 가능
- 속성은 객체의 상태를 나타내는 변수이고, 메서드는 객체의 동작을 정의하는 함수
- 생성자(constructor)라는 특별한 메서드를 가지고 있으며, 객체를 생성할 때 초기화 작업 수행
- 클래스는 여러 개의 객체를 생성할 수 있으며, 각각의 객체는 독립적인 상태와 동작을 가질 수 있다.
기본 문법
class ClassName {
constructor() {
// 객체 초기화 작업 수행
}
method1() {
// 메서드 동작 정의
}
method2() {
// 메서드 동작 정의
}
}
let obj = new ClassName(); // 클래스의 객체 생성
특징
프로토타입 기반 상속
- 자바스크립트의 클래스는 프로토타입 기반 상속을 지원
- 클래스를 정의할 때, 프로토타입 체인을 통해 다른 클래스의 속성과 메서드를 상속
- 예시
// 부모 클래스
function Animal(name) {
this.name = name;
}
// 메서드 추가
Animal.prototype.sayName = function() {
console.log("My name is " + this.name);
}
// 자식 클래스
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// 프로토타입 체인 설정
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 자식 클래스의 메서드 추가
Dog.prototype.bark = function() {
console.log("Woof!");
}
// 객체 생성
var myDog = new Dog("Max", "Labrador");
myDog.sayName(); // 출력: My name is Max
myDog.bark(); // 출력: Woof!
생성자 함수
- 클래스는 생성자(constructor) 함수를 통해 객체를 초기화
- 생성자 함수는 클래스의 인스턴스를 생성할 때 자동으로 호출되며, 초기화 작업을 수행
- 예시
// 클래스 정의
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
// 객체 생성
let person = new Person("John", 25);
person.introduce(); // 출력: Hi, my name is John and I'm 25 years old.
메서드 정의
- 클래스 내에서 메서드는 일반 함수 형태로 정의
- 클래스의 메서드는 객체의 동작을 정의하며, 클래스의 인스턴스에서 호출
정적 메서드
- 정적(static) 메서드는 클래스 자체에 속한 메서드로서, 인스턴스를 생성하지 않고도 호출할 수 있다.
- 정적 메서드는 클래스의 동작과 관련된 유틸리티 함수를 구현하는데 사용
- 예시
// 클래스 정의
class MathUtils {
static multiply(a, b) {
return a * b;
}
}
// 정적 메서드 호출
let result = MathUtils.multiply(5, 3);
console.log(result); // 출력: 15
상속
- 클래스는 다른 클래스를 상속 가능
- 상속을 통해 부모 클래스의 속성과 메서드를 자식 클래스가 상속 받아 사용
- 상속을 하면 코드의 재상용성과 확장성을 향상
- 예시
// 부모 클래스
class Shape {
constructor(color) {
this.color = color;
}
getColor() {
return this.color;
}
}
// 자식 클래스
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
getArea() {
return Math.PI * this.radius * this.radius;
}
}
// 객체 생성
let circle = new Circle("red", 5);
console.log(circle.getColor()); // 출력: red
console.log(circle.getArea()); // 출력: 78.53981633974483
Getter와 Setter
- 클래스 내에서 속성을 접근하기 위해 Getter와 Setter를 사용할 수 있다.
- Getter는 속성 값을 반환, Setter는 속성 값을 설정
- 속성에 접근하는 동안 추가적인 동작을 수행
- 예시
// 클래스 정의
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get width() {
return this._width;
}
set width(value) {
if (value > 0) {
this._width = value;
} else {
console.log("Width must be a positive number.");
}
}
get height() {
return this._height;
}
set height(value) {
if (value > 0) {
this._height = value;
} else {
console.log("Height must be a positive number.");
}
}
getArea() {
return this._width * this._height;
}
}
// 객체 생성
let rectangle = new Rectangle(10, 20);
console.log(rectangle.getArea()); // 출력: 200
rectangle.width = 5;
rectangle.height = -2;
console.log(rectangle.getArea()); // 출력: 50 (width와 height가 변경되지 않았으므로 이전 값이 유지됨)
클래스 상속의 확장
- ES6부터 도입된 클래스는 기존의 프로토타입 기반 상속을 확장한 개념
- 클래스를 확장하여 새로운 클래스를 생성
- 상속된 메서드를 오버라이딩하거나 추가적인 메서드를 정의
'프론트엔드 > JavaScript' 카테고리의 다른 글
[자바스크립트] require와 import의 개념과 차이점 (0) | 2023.12.04 |
---|---|
[자바스크립트] 함수에 대해 (0) | 2023.11.20 |
[자바스크립트] 스코프에 대해 (1) | 2023.11.17 |
[자바스크립트] == 과 === 에 대해서 (0) | 2023.11.14 |
[자바스크립트] Map과 Set (1) | 2023.11.13 |