코딩 스쿨 JavaScript

언어선택 : HTMLCSSJAVAJAVASCRIPTMYSQLSQL PHP
▶ JavaScript Tutorial
JavaScript HOME
JavaScript Introduction
JavaScript Where To
JavaScript Output
JavaScript Statements
JavaScript Syntax
JavaScript Comments
JavaScript Variables
JavaScript Let
JavaScript Const
JavaScript Operators
JavaScript Arithmetic
JavaScript Assignment
JavaScript Data Types
JavaScript Functions
JavaScript Objects
JavaScript Object Properties
JavaScript Object Methods
JavaScript Object Display
JavaScript Object Constructors
JavaScript Events
JavaScript Strings
JavaScript String Methods
JavaScript String Search
JavaScript String Templates
JavaScript Numbers
JavaScript BigInt
JavaScript Number Methods
JavaScript Number Properties
JavaScript Arrays
JavaScript Array Methods
JavaScript Array Search
JavaScript Array Sort
JavaScript Array Iteration
JavaScript Array Const
JavaScript Dates
JavaScript Date Formats
JavaScript Date Get Methods
JavaScript Date Set Methods
JavaScript Math
JavaScript Random
JavaScript Booleans
JavaScript Comparisons
JavaScript If Else
JavaScript Switch
JavaScript Loop For
JavaScript Loop For In
JavaScript Loop For Of
JavaScript Loop While
JavaScript Break
JavaScript Iterables
JavaScript Sets
JavaScript Set Methods
JavaScript Maps
JavaScript Map Methods
JavaScript Typeof
JavaScript Type Conversion
JavaScript Destructuring
JavaScript Bitwise
JavaScript RegExp
JavaScript Precedence
JavaScript Errors
JavaScript Scope
JavaScript Hoisting
JavaScript Strict Mode
JavaScript this Keyword
JavaScript Arrow Function
JavaScript Classes
JavaScript Modules
JavaScript JavaScriptON
JavaScript Debugging
JavaScript Style Guide
JavaScript Best Practices
JavaScript Mistakes
JavaScript Performance
JavaScript Reserved Words

JavaScript Object Methods

JavaScript Object Methods: 이해와 활용

JavaScript의 **객체(Object)**는 메서드(method)를 통해 데이터를 조작하고 기능을 수행하는 중요한 단위입니다. 이 가이드는 JavaScript 객체의 다양한 메서드에 대한 이해를 높이고, 이를 효과적으로 활용하는 방법을 제공합니다.


1. 객체 메서드란?

  • *메서드(Method)**는 객체 내에 정의된 함수로, 객체의 동작을 나타냅니다. 메서드는 객체의 프로퍼티를 조작하거나, 객체와 관련된 작업을 수행하는 데 사용됩니다.

1.1. 메서드 정의

const person = {
    name: "Alice",
    age: 30,
    greet() { // 메서드 정의
        console.log(`Hello, my name is ${this.name}`);
    }
};

person.greet(); // 출력: Hello, my name is Alice


2. 객체의 메서드 유형

JavaScript에서 객체의 메서드는 크게 **정적 메서드(Static Methods)**와 **인스턴스 메서드(Instance Methods)**로 나눌 수 있습니다.

2.1. 인스턴스 메서드

인스턴스 메서드는 특정 객체에 속하는 메서드입니다. 객체의 속성에 접근할 수 있으며, this 키워드를 사용하여 해당 객체를 참조합니다.

const rectangle = {
    width: 10,
    height: 5,
    area() { // 인스턴스 메서드
        return this.width * this.height;
    }
};

console.log(rectangle.area()); // 출력: 50

2.2. 정적 메서드

정적 메서드는 클래스나 객체 자체에 속하며, 인스턴스와는 독립적으로 호출됩니다. 정적 메서드는 this가 클래스나 객체를 참조하지 않고, 주로 유틸리티 함수에 사용됩니다.

class MathUtil {
    static add(x, y) { // 정적 메서드
        return x + y;
    }
}

console.log(MathUtil.add(5, 3)); // 출력: 8


3. 객체 메서드의 종류

JavaScript 객체에는 다양한 내장 메서드가 제공됩니다. 이들 메서드는 객체를 조작하고, 정보를 얻는 데 유용합니다.

3.1. Object.keys()

객체의 모든 프로퍼티 이름을 배열로 반환합니다.

const person = {
    name: "Alice",
    age: 30,
    occupation: "Engineer"
};

const keys = Object.keys(person);
console.log(keys); // 출력: ["name", "age", "occupation"]

3.2. Object.values()

객체의 모든 프로퍼티 값을 배열로 반환합니다.

const values = Object.values(person);
console.log(values); // 출력: ["Alice", 30, "Engineer"]

3.3. Object.entries()

객체의 키-값 쌍을 배열의 배열 형태로 반환합니다.

const entries = Object.entries(person);
console.log(entries);
// 출력: [["name", "Alice"], ["age", 30], ["occupation", "Engineer"]]

3.4. Object.assign()

두 개 이상의 객체를 병합하여 하나의 객체로 만듭니다. 새로운 객체를 반환하며, 기존 객체는 변경되지 않습니다.

const target = { a: 1 };
const source = { b: 2, c: 3 };

const merged = Object.assign({}, target, source);
console.log(merged); // 출력: { a: 1, b: 2, c: 3 }

3.5. Object.freeze()

객체를 동결하여 프로퍼티의 추가, 수정, 삭제를 방지합니다.

const config = {
    apiEndpoint: "<https://api.example.com>",
    timeout: 5000
};

Object.freeze(config);
config.timeout = 3000; // 변경되지 않음
console.log(config.timeout); // 출력: 5000

3.6. Object.seal()

객체의 프로퍼티를 잠그지만, 기존 프로퍼티의 값을 수정할 수 있습니다. 프로퍼티의 추가나 삭제는 불가능합니다.

const user = {
    name: "Helen",
    age: 29
};

Object.seal(user);
user.age = 30; // 수정 가능
delete user.name; // 삭제되지 않음
console.log(user); // 출력: { name: "Helen", age: 30 }

3.7. Object.create()

주어진 프로토타입을 가진 새 객체를 생성합니다.

const animal = {
    speak() {
        console.log(`${this.name} makes a noise.`);
    }
};

const dog = Object.create(animal);
dog.name = "Buddy";
dog.speak(); // 출력: Buddy makes a noise.

3.8. Object.getPrototypeOf()

객체의 프로토타입을 반환합니다.

const proto = Object.getPrototypeOf(dog);
console.log(proto); // 출력: { speak: [Function: speak] }

3.9. Object.setPrototypeOf()

객체의 프로토타입을 설정합니다.

const cat = {
    name: "Whiskers"
};

Object.setPrototypeOf(cat, animal);
cat.speak(); // 출력: Whiskers makes a noise.

3.10. Object.is()

두 값이 동일한지 비교합니다. NaN을 포함하여 모든 값의 동등성을 검사할 수 있습니다.

console.log(Object.is("foo", "foo")); // 출력: true
console.log(Object.is(window, window)); // 출력: true
console.log(Object.is([], [])); // 출력: false
console.log(Object.is(NaN, NaN)); // 출력: true


4. 객체 메서드의 활용

객체 메서드는 데이터 조작 및 구조화에 유용하며, 다양한 활용 방법이 있습니다.

4.1. 데이터 구조화

객체 메서드를 활용하여 복잡한 데이터를 효과적으로 구조화할 수 있습니다.

const students = {
    Alice: { age: 20, grade: "A" },
    Bob: { age: 22, grade: "B" },
    Charlie: { age: 21, grade: "C" }
};

// 모든 학생의 이름과 학년 출력
Object.entries(students).forEach(([name, info]) => {
    console.log(`${name}: ${info.grade}`);
});

4.2. 데이터 병합 및 업데이트

여러 객체를 병합하거나 업데이트하여 상태 관리를 쉽게 할 수 있습니다.

const defaultSettings = {
    theme: "light",
    notifications: true
};

const userSettings = {
    notifications: false
};

const finalSettings = Object.assign({}, defaultSettings, userSettings);
console.log(finalSettings); // 출력: { theme: "light", notifications: false }

4.3. 객체의 안전성 강화

Object.freeze()Object.seal()을 사용하여 객체의 상태를 보호하고, 의도하지 않은 변경을 방지할 수 있습니다.

const config = {
    apiEndpoint: "<https://api.example.com>",
    timeout: 5000
};

Object.freeze(config);

// 변경 불가능
config.apiEndpoint = "<https://api.new-url.com>"; // 무시됨
console.log(config.apiEndpoint); // 출력: <https://api.example.com>


5. 결론

JavaScript의 객체 메서드는 객체를 관리하고 조작하는 데 필수적인 도구입니다. 이 메서드들을 이해하고 활용하면 더 나은 코드 구조와 재사용성을 확보할 수 있습니다. 다양한 예제를 통해 객체 메서드의 동작 방식을 직접 확인하고, 실무에 적용해보세요!


copyright ⓒ 스타트코딩 all rights reserved.
이메일 : startcodingim@gamil.com