JS/JavaScript

#16 자바스크립트 프로토타입 체인

인생아 2024. 8. 31. 00:20
반응형

자바스크립트에서 객체는 프로토타입 기반(prototype-based) 언어의 특성을 가집니다. 이로 인해 객체는 다른 객체를 상속받을 수 있으며, 이를 통해 객체 간에 속성과 메서드를 공유할 수 있습니다. 이러한 객체 상속 구조를 **프로토타입 체인(Prototype Chain)**이라고 부릅니다.

프로토타입(Prototype)이란?

자바스크립트에서 모든 객체는 __proto__라는 숨겨진 속성을 가집니다. 이 속성은 객체의 프로토타입을 가리키며, 다른 객체로부터 상속받은 속성과 메서드를 정의합니다. 모든 객체는 자신의 프로토타입 객체로부터 속성과 메서드를 상속받습니다.

기본 프로토타입 예제

const person = {
    name: 'John',
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

const john = Object.create(person);
john.greet(); // "Hello, my name is John"

위의 예제에서 john 객체는 person 객체를 프로토타입으로 가지고 있습니다. 따라서 john은 자신의 속성으로 name과 greet 메서드를 가지지 않지만, person 객체로부터 상속받아 greet 메서드를 호출할 수 있습니다.

프로토타입 체인(Prototype Chain)

프로토타입 체인은 한 객체가 다른 객체의 프로토타입을 참조하는 구조입니다. 자바스크립트에서 객체의 속성이나 메서드에 접근할 때, 먼저 해당 객체에서 직접 찾아보고, 없으면 프로토타입 체인을 따라 상위 객체에서 찾습니다. 이 과정은 최상위 객체인 Object.prototype에 도달할 때까지 계속됩니다.

프로토타입 체인 예제

const animal = {
    eat() {
        console.log('Eating...');
    }
};

const dog = Object.create(animal);
dog.bark = function() {
    console.log('Barking...');
};

dog.bark(); // "Barking..."
dog.eat();  // "Eating..."

console.log(dog.hasOwnProperty('bark')); // true
console.log(dog.hasOwnProperty('eat'));  // false

위의 예제에서 dog 객체는 animal 객체를 프로토타입으로 상속받습니다. dog는 bark 메서드를 가지고 있지만 eat 메서드는 직접적으로 가지지 않고, 프로토타입 체인을 통해 animal 객체로부터 상속받습니다.

생성자 함수와 프로토타입

생성자 함수(Constructor Function)를 사용하여 새로운 객체를 만들면, 해당 객체는 생성자 함수의 prototype 속성을 참조합니다. 생성자 함수의 prototype 객체에 정의된 속성과 메서드는 해당 생성자로 생성된 모든 객체에서 공유됩니다.

생성자 함수와 프로토타입 예제

function Person(name) {
    this.name = name;
}

Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};

const alice = new Person('Alice');
const bob = new Person('Bob');

alice.greet(); // "Hello, my name is Alice"
bob.greet();   // "Hello, my name is Bob"

console.log(alice.__proto__ === Person.prototype); // true
console.log(Person.prototype.constructor === Person); // true

위의 예제에서 Person 생성자 함수를 사용해 alice와 bob 객체를 생성했습니다. Person.prototype에 정의된 greet 메서드는 alice와 bob 객체에서 모두 공유됩니다.

프로토타입 체인의 최상위: Object.prototype

자바스크립트의 모든 객체는 최종적으로 Object.prototype을 프로토타입 체인의 최상위로 가집니다. Object.prototype은 자바스크립트에서 가장 기본이 되는 객체로, 모든 객체에 공통적으로 사용되는 메서드(toString, hasOwnProperty 등)를 포함하고 있습니다.

Object.prototype 예제

const obj = {};

console.log(obj.toString()); // "[object Object]"
console.log(obj.hasOwnProperty('toString')); // false

위의 예제에서 obj 객체는 자신의 속성으로 toString 메서드를 가지지 않지만, Object.prototype으로부터 상속받아 사용할 수 있습니다.

프로토타입 체인의 활용

프로토타입 체인을 통해 객체 간에 속성과 메서드를 공유할 수 있습니다. 이 방식은 메모리 효율성을 높이고, 객체지향적인 설계를 가능하게 합니다. 예를 들어, 여러 객체가 공통으로 사용할 메서드를 프로토타입에 정의하면, 각 객체에 중복 정의하지 않아도 됩니다.

프로토타입 체인 활용 예제

function Car(model) {
    this.model = model;
}

Car.prototype.drive = function() {
    console.log(`${this.model} is driving.`);
};

const tesla = new Car('Tesla Model 3');
const bmw = new Car('BMW X5');

tesla.drive(); // "Tesla Model 3 is driving."
bmw.drive();   // "BMW X5 is driving."

위의 예제에서 Car.prototype에 drive 메서드를 정의함으로써, tesla와 bmw 객체가 이를 공통적으로 사용할 수 있습니다.

결론

자바스크립트의 프로토타입 체인은 객체지향 프로그래밍의 핵심적인 개념입니다. 이를 통해 객체 간에 속성과 메서드를 효율적으로 상속하고 공유할 수 있습니다. 프로토타입 체인을 잘 이해하고 활용하면, 자바스크립트 코드의 재사용성을 높이고, 메모리 효율성을 개선할 수 있습니다.

반응형