πŸ’» Programming

Prototype

Prototype

JavaScript's core inheritance mechanism. A way for objects to inherit properties and methods from other objects through the prototype chain.

πŸ“– Detailed Explanation

Prototype is the core mechanism for implementing object-oriented programming in JavaScript. Unlike class-based languages such as Java and C++, JavaScript uses prototype-based inheritance. Every JavaScript object internally has a [[Prototype]] slot that references another object, and this referenced object is the prototype. When looking up a particular property or method on an object, if it is not found on that object, the search continues in the prototype object.

Prototype Chain refers to a structure in which objects are linked through prototypes. When looking up a property on an object, the JavaScript engine first checks the object's own properties, and if it is not found, checks the object that [[Prototype]] points to. This process continues until the property is found or the end of the chain (null) is reached. For example, when toString() is called on an array object, the method is found by searching through Array.prototype up to Object.prototype.

__proto__ and prototype are concepts that are easy to confuse. prototype is a property that only function objects have, and it points to the object that will become the [[Prototype]] of instances created with the new keyword. In contrast, __proto__ is an accessor property that every object has, and it points to the object's actual [[Prototype]]. That is, constructorFunction.prototype === instance.__proto__ holds true. However, since __proto__ is a legacy feature, using Object.getPrototypeOf() and Object.setPrototypeOf() is recommended.

ES6 class syntax is syntactic sugar that makes prototype-based inheritance more intuitive to use. Even when declared with the class keyword, the prototype chain still operates internally. Methods of a class are automatically added to the prototype, and the extends keyword sets up the prototype chain. Therefore, even when using class syntax, understanding the concept of prototypes is essential for working with JavaScript in depth.

πŸ’» Code Example

prototype-inheritance.js - Prototype inheritance
// μƒμ„±μž ν•¨μˆ˜λ₯Ό ν†΅ν•œ ν”„λ‘œν† νƒ€μž… 상속
function Animal(name) {
    this.name = name;
}

// prototype에 λ©”μ„œλ“œ μΆ”κ°€ (λͺ¨λ“  μΈμŠ€ν„΄μŠ€κ°€ 곡유)
Animal.prototype.speak = function() {
    console.log(`${this.name}κ°€ μ†Œλ¦¬λ₯Ό λƒ…λ‹ˆλ‹€.`);
};

Animal.prototype.sleep = function() {
    console.log(`${this.name}κ°€ μž μ„ μž‘λ‹ˆλ‹€.`);
};

// μžμ‹ μƒμ„±μž ν•¨μˆ˜
function Dog(name, breed) {
    // λΆ€λͺ¨ μƒμ„±μž 호좜 (super μ—­ν• )
    Animal.call(this, name);
    this.breed = breed;
}

// ν”„λ‘œν† νƒ€μž… 체인 μ„€μ • (상속)
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// Dog만의 λ©”μ„œλ“œ μΆ”κ°€
Dog.prototype.bark = function() {
    console.log(`${this.name}κ°€ 멍멍 μ§–μŠ΅λ‹ˆλ‹€!`);
};

// λ©”μ„œλ“œ μ˜€λ²„λΌμ΄λ”©
Dog.prototype.speak = function() {
    console.log(`${this.name}(${this.breed})κ°€ μ™ˆμ™ˆ!`);
};

// μΈμŠ€ν„΄μŠ€ 생성 및 ν…ŒμŠ€νŠΈ
const myDog = new Dog('바둑이', 'μ§„λ—κ°œ');

myDog.speak();  // 바둑이(μ§„λ—κ°œ)κ°€ μ™ˆμ™ˆ!
myDog.sleep();  // 바둑이가 μž μ„ μž‘λ‹ˆλ‹€. (상속받은 λ©”μ„œλ“œ)
myDog.bark();   // 바둑이가 멍멍 μ§–μŠ΅λ‹ˆλ‹€!

// ν”„λ‘œν† νƒ€μž… 체인 확인
console.log(myDog instanceof Dog);    // true
console.log(myDog instanceof Animal); // true
console.log(Dog.prototype.isPrototypeOf(myDog)); // true
object-create.js - Using Object.create
// Object.create()λ₯Ό μ‚¬μš©ν•œ ν”„λ‘œν† νƒ€μž… 상속
// 더 λͺ…μ‹œμ μ΄κ³  μœ μ—°ν•œ 상속 방식

const personProto = {
    greet() {
        console.log(`μ•ˆλ…•ν•˜μ„Έμš”, ${this.name}μž…λ‹ˆλ‹€.`);
    },
    introduce() {
        console.log(`μ €λŠ” ${this.age}살이고, ${this.job}μž…λ‹ˆλ‹€.`);
    }
};

// Object.create둜 ν”„λ‘œν† νƒ€μž… μ„€μ •
const developer = Object.create(personProto, {
    // ν”„λ‘œνΌν‹° λ””μŠ€ν¬λ¦½ν„°λ‘œ μ„Έλ°€ν•œ μ œμ–΄ κ°€λŠ₯
    name: {
        value: 'κΉ€κ°œλ°œ',
        writable: true,
        enumerable: true
    },
    age: {
        value: 28,
        writable: true,
        enumerable: true
    },
    job: {
        value: 'ν”„λ‘ νŠΈμ—”λ“œ 개발자',
        writable: true,
        enumerable: true
    }
});

// 개발자만의 λ©”μ„œλ“œ μΆ”κ°€
developer.code = function(language) {
    console.log(`${this.name}κ°€ ${language}둜 μ½”λ”©ν•©λ‹ˆλ‹€.`);
};

developer.greet();     // μ•ˆλ…•ν•˜μ„Έμš”, κΉ€κ°œλ°œμž…λ‹ˆλ‹€.
developer.introduce(); // μ €λŠ” 28살이고, ν”„λ‘ νŠΈμ—”λ“œ κ°œλ°œμžμž…λ‹ˆλ‹€.
developer.code('JavaScript'); // κΉ€κ°œλ°œκ°€ JavaScript둜 μ½”λ”©ν•©λ‹ˆλ‹€.

// ν”„λ‘œν† νƒ€μž… 확인
console.log(Object.getPrototypeOf(developer) === personProto); // true

// null ν”„λ‘œν† νƒ€μž…μœΌλ‘œ 순수 λ”•μ…”λ„ˆλ¦¬ 객체 생성
const pureDict = Object.create(null);
pureDict.key = 'value';
console.log(pureDict.hasOwnProperty); // undefined (상속 μ—†μŒ)
proto-vs-prototype.js - Difference between __proto__ and prototype
// __proto__ vs prototype μ΄ν•΄ν•˜κΈ°

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

Person.prototype.sayHello = function() {
    console.log(`Hello, I'm ${this.name}`);
};

const john = new Person('John');

// prototype: ν•¨μˆ˜ 객체의 ν”„λ‘œνΌν‹°
// 이 ν•¨μˆ˜λ‘œ 생성될 μΈμŠ€ν„΄μŠ€μ˜ [[Prototype]]이 될 객체
console.log(Person.prototype);
// { sayHello: [Function], constructor: Person }

// __proto__: λͺ¨λ“  객체의 [[Prototype]] μ ‘κ·Όμž
// ν•΄λ‹Ή 객체가 μ‹€μ œλ‘œ μƒμ†λ°›λŠ” ν”„λ‘œν† νƒ€μž… 객체
console.log(john.__proto__);
// { sayHello: [Function], constructor: Person }

// 핡심: λ‘˜μ€ 같은 객체λ₯Ό μ°Έμ‘°!
console.log(john.__proto__ === Person.prototype); // true

// ꢌμž₯: __proto__ λŒ€μ‹  Object.getPrototypeOf() μ‚¬μš©
console.log(Object.getPrototypeOf(john) === Person.prototype); // true

// ν”„λ‘œν† νƒ€μž… 체인 μ‹œκ°ν™”
console.log(john.__proto__);                      // Person.prototype
console.log(john.__proto__.__proto__);             // Object.prototype
console.log(john.__proto__.__proto__.__proto__);    // null (체인의 끝)

// ν”„λ‘œνΌν‹° 검색 κ³Όμ •
// 1. john.name -> john κ°μ²΄μ—μ„œ 발견 -> "John"
// 2. john.sayHello -> john에 μ—†μŒ -> Person.prototypeμ—μ„œ 발견
// 3. john.toString -> Person.prototype에 μ—†μŒ -> Object.prototypeμ—μ„œ 발견

πŸ—£οΈ Practical Conversation Examples

Technical Interview Explaining the Prototype Chain

Interviewer:

"What is the prototype chain in JavaScript, and how does it work? Please explain."

Candidate:

"The prototype chain is JavaScript's inheritance mechanism. Every object references another object through an internal slot called [[Prototype]]. When looking up a property on an object, it first checks its own properties, and if it is not found, it searches the object that [[Prototype]] points to. This process happens in succession until it reaches null, which is why it is called a 'chain'."

Interviewer:

"Then why is it possible to call methods like forEach on an array?"

Candidate:

"It is because the [[Prototype]] of an array instance points to Array.prototype. Array methods such as forEach, map, and filter are defined on Array.prototype, so all array instances share them through the prototype chain. Likewise, this is why toString and hasOwnProperty of Object.prototype can be used on all objects."

Interviewer:

"Is there anything to watch out for regarding the performance of the prototype chain?"

Candidate:

"The longer the chain gets, the more the property lookup time increases. In particular, when looking up a property that does not exist, the entire chain must be traversed, which can affect performance. Also, changing the prototype at runtime invalidates the V8 engine's hidden class optimization, which degrades performance. Therefore, it is best to change prototypes only at initialization time."

Code Review Discussion: class vs prototype

Senior Developer:

"In this code, inheritance is implemented with a constructor function and prototype. How about refactoring it to ES6 class syntax?"

Junior Developer:

"class is more readable, but does it work differently under the hood? When using class, is inheritance done in a way other than prototypes?"

Senior Developer:

"No, class is just syntactic sugar. Internally, it uses the prototype chain in the same way. Methods of a class are automatically added to the prototype, and extends sets up the chain through Object.setPrototypeOf. However, there are differences: class is always in strict mode and is not hoisted."

Tech Lead:

"Our team convention recommends using class, so it would be good to refactor. However, you must understand the prototype concept well. It is essential when checking __proto__ while debugging or analyzing library code."

Junior Developer:

"Understood! I will convert it to class, while remembering that the underlying principle is the prototype. By the way, are private fields (#) and static methods in class also related to prototypes?"

Senior Developer:

"Static methods are added not to the prototype but as properties of the constructor function itself. That is why they cannot be called on instances. Private fields (#) are a completely new feature, and are encapsulated in each instance regardless of the prototype."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More