Javascript => 객체 지향 프로그래밍 언어
클래스가 없어서 객체지향이 아니라고 생각하는 사람들도 있으나 프로토타입 기반의 객체지향 언어다.
객체의 특징
- 다양한 타입의 값을 하나의 단위로 구성
- 변경 가능
- 0개 이상의 프로퍼티로 구성 / 프로퍼티는 key : value 로 구성
- function도 프로퍼티의 값으로 설정 가능 : 이때 일반 함수와 구분하기 위해 method 라 칭한다.
(프로퍼티 : 객체의 상태를 나타내는 값)
자바스크립트는 클래스 개념이 없고 별도의 객체 생성 방법이 존재한다.
=> ES6 부터는 클래스도 지원한다!
- 객체 리터럴
- object 생성자 함수
- 생성자 함수
- Object.create 메서드
- 클래스(ES6)
여기서 객체 리터럴 이란?
객체를 표현할 때 , 중괄호 {} 를 사용하여 나타내는 방식
var obj1 = {};
obj1.name = 'Lee';
var person = {
name: "Wi",
sayHello: function () {
console.log(`Hello My name is ${this.name}`);
},
};
중괄호 내에 0개 이상의 프로퍼티를 정의한다.
변수에 할당되는 시점에 JS 엔진은 객체 리터럴을 해석해 객체를 생성한다.
객체 리터럴 팁들
기본
1. 속성 이름 축약
객체의 속성 이름과 변수 이름이 같을 경우, 속성 이름을 생략하고 변수 이름만 작성할 수 있습니다.
const name = 'John Doe';
const age = 30;
// 전통적인 방식
const person = {
name: name,
age: age,
};
// 속성 이름 축약
const personShorthand = {
name,
age,
};
2. 계산된 속성 이름
대괄호 []를 사용하여 객체 리터럴 내에서 속성 이름을 동적으로 생성할 수 있습니다.
const uniqueKey = 'userId';
const user = {
[uniqueKey]: '12345',
name: 'Jane Doe',
};
console.log(user.userId); // '12345'
3. 메서드 정의 축약
객체 내에서 함수를 정의할 때 function 키워드를 생략할 수 있습니다.
const calculator = {
add(x, y) {
return x + y;
},
subtract(x, y) {
return x - y;
},
};
console.log(calculator.add(5, 3)); // 8
console.log(calculator.subtract(5, 3)); // 2
4. 객체 분해 할당
객체의 속성을 변수로 쉽게 추출할 수 있습니다.
const person = {
name: 'John Doe',
age: 30,
};
const { name, age } = person;
console.log(name); // 'John Doe'
console.log(age); // 30
5. 객체 전개 연산자 (Spread Operator)
객체의 속성을 다른 객체에 쉽게 복사할 수 있습니다.
const user = {
name: 'Jane Doe',
age: 28,
};
const userWithId = {
...user,
id: '12345',
};
console.log(userWithId); // { name: 'Jane Doe', age: 28, id: '12345' }
6. 객체 리터럴을 사용한 설정 옵션
객체 리터럴은 설정 옵션을 정의할 때 매우 유용합니다.
useTopping({
onStart: () => {
console.log('onStart');
},
onStop: () => {
console.log('onStop');
},
onDestroy: () => {
console.log('onDestroy');
},
});
심화
1. 함수 바인딩과 객체 리터럴
객체 리터럴 내에서 메서드를 정의할 때, 해당 메서드가 외부에서 호출될 경우 this 바인딩이 예상치 못한 방식으로 작동할 수 있습니다. 이를 해결하기 위해 생성자 함수 내에서 객체 리터럴을 반환하고, 화살표 함수를 사용하여 this를 올바르게 바인딩할 수 있습니다.
function createUser(name, age) {
return {
name,
age,
greet: () => {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
},
};
}
const user = createUser('John Doe', 30);
user.greet(); // "Hello, my name is John Doe and I am 30 years old."
2. 프로토타입 상속과 객체 생성
Object.create()를 사용하여 객체를 생성할 때 특정 프로토타입을 상속받게 할 수 있습니다. 이를 통해 객체 지향 프로그래밍 패턴을 더 쉽게 구현할 수 있습니다.
const personPrototype = {
greet() {
console.log(`Hello, my name is ${this.name}`);
},
};
const person = Object.create(personPrototype);
person.name = 'Jane Doe';
person.greet(); // "Hello, my name is Jane Doe"
const animal = {
type: 'Animal',
displayType: function() {
console.log(this.type);
}
};
// animal 객체를 프로토타입으로 하는 새 객체 cat을 생성
const cat = Object.create(animal);
cat.type = 'Cat'; // 프로퍼티 오버라이드
animal.displayType(); // 출력: Animal
cat.displayType(); // 출력: Cat
3. 객체 리터럴과 비구조화 할당을 이용한 조건부 속성 추가
객체 리터럴 내에서 조건에 따라 속성을 추가하고 싶을 때, 스프레드 연산자(...)와 비구조화 할당을 활용할 수 있습니다.
const createUser = (name, age, bio) => ({
name,
age,
...(bio ? { bio } : {}),
});
const userWithBio = createUser('John Doe', 30, 'Software Developer');
const userWithoutBio = createUser('Jane Doe', 25);
console.log(userWithBio); // { name: 'John Doe', age: 30, bio: 'Software Developer' }
console.log(userWithoutBio); // { name: 'Jane Doe', age: 25 }
4. 객체 리터럴과 Map 객체
복잡한 데이터 구조를 다룰 때, 객체 리터럴 대신 Map 객체를 사용하는 것이 더 적합할 수 있습니다. Map은 키로 어떤 타입의 값을 사용할 수 있으며, 순서를 유지합니다.
크기가 큰 데이터 집합에서 키에 대한 검색, 삭제, 추가 작업이 빈번히 발생할 때 객체 리터럴보다 성능적으로 유리할 수 있습니다.
다양한 타입의 키를 사용하거나, 삽입 순서가 중요한 경우 Map 객체는 객체 리터럴보다 더 적합할 수 있습니다.
const settings = new Map([
['theme', 'dark'],
['notifications', true],
]);
settings.set('fontSize', 14);
for (const [key, value] of settings) {
console.log(`${key}: ${value}`);
}
5. 동적 속성 이름과 계산된 메서드 이름
속성 이름 뿐만 아니라 메서드 이름도 동적으로 생성할 수 있습니다. 이를 통해 더 동적이고 유연한 객체를 생성할 수 있습니다.
const methodName = 'greet';
const user = {
[methodName]() {
console.log('Hello, World!');
},
};
user.greet(); // "Hello, World!"
'웹' 카테고리의 다른 글
JS - 스코프(Scope) (0) | 2024.04.24 |
---|---|
Babel 이란? +babel-plugin-macros (1) | 2024.04.19 |
React-Hook-Form 심화 watch / useWatch / controll / register / wizard form (0) | 2024.04.11 |
React Hook Form 훑어보기 (0) | 2024.04.08 |
CRA , VITE 에서 .env 파일 사용하기 (0) | 2023.03.23 |