JavaScript Prototype

nara_lee·2025년 4월 3일

What is prototype

const obj={};
console.log(Object.getPrototyoeOf(obj) === Object.prototype); // true

In JavaScript, the concept of the prototype is fundamental to how objects inherit behavior from each other.

1. Objects and the Prototype Chain

  • Every JavaScript object has an internal link to another object, known as its prototype (often denoted [[Prototype]]).
  • The prototype object itself may have a prototype, and so on, forming a prototype chain.
  • When you try to access a property on an object, JavaScript first looks on the object itself. If the property is not found, it looks on the object’s prototype, then on the prototype’s prototype, and so forth, until either the property is found or the chain ends (e.g., Object.prototype).

Objects Created via Object Literals

  • When you create an object with curly braces (e.g., const obj = { ... };), its internal [[Prototype]] is Object.prototype by default (unless you use special methods like Object.create to change this).
  • This means it inherits methods such as toString or hasOwnProperty from Object.prototype.

Object.create

  • One of the most direct ways to set an object’s prototype is Object.create(proto).
  • It creates a new object whose internal [[Prototype]] is explicitly set to proto.
  • Example:
    const animal = {
      move() { console.log("I am moving!"); }
    };
    const cat = Object.create(animal);
    cat.move(); // "I am moving!"
    cat doesn’t have move itself, but its prototype is animal, which has move.

ES6 Classes

  • Although you often see “class-based” syntax in modern JavaScript, such as:
    class Person {
      constructor(name) {
        this.name = name;
      }
      greet() {
        console.log(`Hello, my name is ${this.name}`);
      }
    }
    const bob = new Person("Bob");
  • Under the hood, this class syntax still uses prototypes. You can think of Person.prototype as the place where greet is stored, and bob’s internal [[Prototype]] pointing to Person.prototype.

2. Function Constructors and Their Prototype Property

프로토타입의 구성요소

  • prototype: 함수 객체가 가지는 프로토타입 객체에 대한 참조
  • constructor: 프로토타입 객체가 자신을 생성한 constructor function 을 가르키는 속성
  • __proto__는 객체의 프로토타입에 접근하는 비표준 방법

주의: __proto__는 deprecated => Object.getPrototypeOf() 사용 권장

function Person(name){ //함수객체
  this.name =name;
}

const person = new Person("Alice"); //new 키워드로 instance 화
console.log(Object.getPrototypeOf(person) === Person.prototype); //true
console.log(Person.prototype.constructor === Person);
  • In JavaScript, functions (including constructor functions) have a public property called prototype.
  • When you write code like:
    function Person(name) {
      this.name = name;
    }
    Person.prototype.greet = function () {
      console.log(`Hello, my name is ${this.name}`);
    };
    let alice = new Person("Alice");
    • Person is a constructor function.
    • The object alice automatically has its internal [[Prototype]] pointing to Person.prototype.
    • Because of that linkage, alice can use the greet method that’s defined on Person.prototype.

3. Modifying Prototypes

  • You can add properties or methods directly onto a constructor’s .prototype object to make them available to all instances created by that constructor.
  • For example, adding Person.prototype.sayGoodbye = ... will make sayGoodbye available to every Person instance, including those created before the method was added (as they share the same prototype).

4. The Prototype Chain in Action

  • When JavaScript looks for a property on an object, it checks:
    1. Does the object itself have the property (own property)?
    2. If not, does its prototype have the property?
    3. If not, does that prototype have it? … and so on.
  • This continues up the chain until it either finds the property or reaches null at the top of the chain.

Summary

  • The prototype is an object that defines properties and methods that are inherited by other objects.
  • Prototypal inheritance in JavaScript means objects can share behavior without needing classical “classes.”
  • Understanding the prototype chain is key to understanding how properties are resolved and how JavaScript objects “inherit” features.

When you see something like XMLHttpRequest.prototype, that object is where all the shared functionality for XMLHttpRequest instances is defined. Each instance you create with new XMLHttpRequest() inherits its methods from XMLHttpRequest.prototype via the prototype chain.


본 후기는 [한글과컴퓨터x한국생산성본부x스나이퍼팩토리] 한컴 AI 아카데미 (B-log) 리뷰로 작성 되었습니다.

#한컴AI아카데미 #AI개발자 #AI개발자교육 #한글과컴퓨터 #한국생산성본부 #스나이퍼팩토리 #부트캠프 #AI전문가양성 #개발자교육 #개발자취업

0개의 댓글