> 웹 프론트엔드 > JS 튜토리얼 > JavaScript의 프로토타입 체인: 상속 및 객체 조회 이해

JavaScript의 프로토타입 체인: 상속 및 객체 조회 이해

Mary-Kate Olsen
풀어 주다: 2024-12-22 20:49:11
원래의
743명이 탐색했습니다.

The Prototype Chain in JavaScript: Understanding Inheritance and Object Lookup

JavaScript의 프로토타입 체인

프로토타입 체인은 JavaScript 상속 모델의 기본 개념입니다. 이는 객체가 다른 객체로부터 속성과 메소드를 상속할 수 있도록 하며 JavaScript에서 상속이 작동하는 방식의 핵심 메커니즘입니다.

프로토타입 체인의 작동 방식

JavaScript에서 객체를 생성하면 프로토타입 역할을 하는 다른 객체에 연결됩니다. 모든 객체에는 프로토타입 객체를 참조하는 숨겨진 내부 속성인 [[Prototype]]이 있습니다.

객체의 속성이나 메소드에 액세스하면 JavaScript는 먼저 해당 객체에 속성이 존재하는지 확인합니다. 그렇지 않은 경우 JavaScript는 객체의 프로토타입에 대한 체인을 찾은 다음 해당 프로토타입의 프로토타입 등을 찾아 Object.prototype(프로토타입 체인의 루트)에 도달할 때까지 찾습니다. 체인의 어떤 수준에서도 속성이나 메서드를 찾을 수 없는 경우 JavaScript는 정의되지 않음을 반환합니다.

프로토타입 체인의 예

// Constructor function for Animal
function Animal(name) {
    this.name = name;
}

// Adding a method to Animal's prototype
Animal.prototype.speak = function() {
    console.log(this.name + " makes a noise.");
};

// Constructor function for Dog
function Dog(name) {
    Animal.call(this, name); // Inherit properties from Animal
}

// Set up the prototype chain so Dog inherits from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // Reset the constructor reference

// Create an instance of Dog
const dog = new Dog("Buddy");
dog.speak();  // Output: "Buddy makes a noise."
로그인 후 복사
로그인 후 복사

이 예에서는:

  • Dog 객체는 프로토타입 체인을 통해 Animal 프로토타입을 상속받습니다.
  • dog.speak()를 호출하면 JavaScript는 먼저 dog 객체에서 speech 메소드를 찾습니다. 거기에 없으면 Dog.prototype을 확인하고 마지막으로 Animal.prototype을 확인합니다.
  • Speak가 Animal.prototype에 존재하므로 찾아서 실행합니다.

프로토타입 체인과 Object.prototype

JavaScript의 모든 개체는 궁극적으로 프로토타입 체인의 최상위 프로토타입 개체인 Object.prototype에서 상속됩니다. 이는 배열, 함수, 사용자 정의 객체와 같은 내장 객체의 인스턴스를 포함한 모든 객체가 Object.prototype에 정의된 메서드와 속성에 액세스할 수 있음을 의미합니다.

const obj = {};
console.log(obj.toString()); // Output: "[object Object]"
// The toString method is inherited from Object.prototype
로그인 후 복사

프로토타입 체인 조회 프로세스

  1. 먼저 JavaScript는 개체 자체에서 속성이나 메서드를 찾습니다.
  2. 다음 속성을 ​​찾을 수 없으면 JavaScript는 객체의 프로토타입을 살펴봅니다.
  3. 그런 다음 프로토타입의 프로토타입을 확인하고 Object.prototype에 도달할 때까지 체인을 계속 이어갑니다.
  4. Object.prototype에서도 해당 속성을 찾을 수 없으면 정의되지 않은 값이 반환됩니다.

프로토타입 체인 시각화

다음 예를 고려해보세요.

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

Person.prototype.sayHello = function() {
    console.log("Hello, " + this.name);
};

const john = new Person("John");

console.log(john.sayHello());  // Output: "Hello, John"
console.log(john.toString());  // Output: "[object Object]"
로그인 후 복사

이 경우 John의 프로토타입 체인은 다음과 같습니다.

// Constructor function for Animal
function Animal(name) {
    this.name = name;
}

// Adding a method to Animal's prototype
Animal.prototype.speak = function() {
    console.log(this.name + " makes a noise.");
};

// Constructor function for Dog
function Dog(name) {
    Animal.call(this, name); // Inherit properties from Animal
}

// Set up the prototype chain so Dog inherits from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // Reset the constructor reference

// Create an instance of Dog
const dog = new Dog("Buddy");
dog.speak();  // Output: "Buddy makes a noise."
로그인 후 복사
로그인 후 복사
  • john은 toString 메소드를 직접 갖고 있지 않기 때문에 JavaScript는 Person.prototype을 살펴보고, 거기에 없으면 Object.prototype을 확인합니다.
  • 마지막으로 Object.prototype에 없으면 정의되지 않은 값을 반환합니다.

결론

JavaScript의 프로토타입 체인은 객체가 다른 객체의 속성과 메서드를 상속받을 수 있도록 하는 강력한 상속 기능을 지원합니다. 프로토타입 체인의 작동 방식을 이해하는 것은 JavaScript를 익히고 보다 효율적인 객체 지향 코드를 만드는 데 중요합니다.

안녕하세요. 저는 Abhay Singh Kathayat입니다!
저는 프론트엔드와 백엔드 기술 모두에 대한 전문 지식을 갖춘 풀스택 개발자입니다. 저는 효율적이고 확장 가능하며 사용자 친화적인 애플리케이션을 구축하기 위해 다양한 프로그래밍 언어와 프레임워크를 사용하여 작업합니다.
제 비즈니스 이메일(kaashshorts28@gmail.com)로 언제든지 연락주세요.

위 내용은 JavaScript의 프로토타입 체인: 상속 및 객체 조회 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿