
자바스크립트는 프로토타입 기반의 프로그래밍 언어로, 객체는 다른 객체를 통해 프로퍼티와 메서드를 상속받을 수 있다. 지금부터 프로토타입이 뭔지 알아보도록 하자.
자바스크립트에서 모든 객체는 [[Prototype]]이라는 내부 슬롯을 가지고 있으며, 이는 해당 객체가 상속받는 다른 객체를 가리킨다.
객체가 특정 프로퍼티나 메서드를 호출할 때, 먼저 자신의 프로퍼티나 메서드에서 존재를 찾고 없으면 프로토타입을 통해 찾는다. 이를 통해 객체 간에 프로퍼티와 메서드를 공유할 수 있다.
new 키워드를 사용해야한다.function Person(name, age) {
this.name = name; // 속성
this.age = age; // 속성
}
// 메서드 추가
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
// 객체 생성
const person1 = new Person("David", 30);
const person2 = new Person("Sean", 26);
person1.greet(); // "Hello, my name is David and I am 30 years old."
person2.greet(); // "Hello, my name is Sean and I am 26 years old."
constructor 메서드 : 클래스 내에서 객체의 초기 상태를 설정하는 역할extends 키워드를 사용하여 기존의 클래스를 확장할 수 있다.class Person {
constructor(name, age) {
this.name = name; // 속성
this.age = age; // 속성
}
greet() { // 메서드
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
class Student extends Person {
greet() { // 메서드
console.log(`Hello, my name is ${this.name} and I am student!`);
}
}
// 객체 생성
const person = new Person("David", 30);
const student = new Student("Sean", 26);
person.greet(); // "Hello, my name is David and I am 30 years old."
student.greet(); // "Hello, my name is Sean and I am student!"
const animal = {
speak() {
console.log("Animal makes a sound.");
}
};
// animal을 프로토타입으로 가지는 dog 객체 생성
const dog = Object.create(animal);
dog.speak = function() {
console.log("Dog barks.");
};
// 메서드 호출
dog.speak(); // "Dog barks."
animal.speak(); // "Animal makes a sound."