Setting Prototypes
Setting Prototypes
Section titled “Setting Prototypes”Introduction
Section titled “Introduction”There are several ways to set an object’s prototype. The recommended modern approach is Object.create(), while __proto__ and Object.setPrototypeOf() are alternatives with trade-offs.
1. Object.create() (Recommended)
Section titled “1. Object.create() (Recommended)”Creates a new object with the specified prototype:
const animal = { eat() { return `${this.name} is eating`; }};
const dog = Object.create(animal);dog.name = 'Rex';console.log(dog.eat()); // 'Rex is eating'console.log(Object.getPrototypeOf(dog) === animal); // trueWith Property Descriptors
Section titled “With Property Descriptors”const obj = Object.create(proto, { name: { value: 'Alice', writable: true, enumerable: true, configurable: true }});2. proto (Deprecated but Common)
Section titled “2. proto (Deprecated but Common)”const dog = { name: 'Rex', __proto__: animal};
console.log(dog.eat()); // 'Rex is eating'
// Also as a setter:dog.__proto__ = animal;⚠️ Deprecated: Works in all environments but is not recommended for production code.
3. Object.setPrototypeOf()
Section titled “3. Object.setPrototypeOf()”const dog = { name: 'Rex' };Object.setPrototypeOf(dog, animal);console.log(dog.eat()); // 'Rex is eating'⚠️ Performance warning: setPrototypeOf can slow down engines — avoid using it after object creation.
4. Constructor’s prototype Property
Section titled “4. Constructor’s prototype Property”function Dog(name) { this.name = name;}
// Setting the prototype for all instancesDog.prototype = animal;
const rex = new Dog('Rex');console.log(rex.eat()); // 'Rex is eating'Getting the Prototype
Section titled “Getting the Prototype”// Modern (recommended)Object.getPrototypeOf(obj);
// Deprecatedobj.__proto__;
// Check if prototype is in chainanimal.isPrototypeOf(dog); // trueComparison
Section titled “Comparison”| Method | Creates New Object | Performance | Modern |
|---|---|---|---|
Object.create() | ✅ Yes | ✅ Best | ✅ Yes |
__proto__ | ❌ No (sets) | ✅ Good | ❌ Deprecated |
Object.setPrototypeOf() | ❌ No (sets) | ❌ Slow | ⚠️ Use sparingly |
Constructor .prototype | ❌ No (sets for instances) | ✅ Good | ✅ Yes |
Best Practices
Section titled “Best Practices”- Use
Object.create()for creating objects with specific prototypes - Set
.prototypeon constructor functions before creating instances - Avoid
Object.setPrototypeOf()on hot paths - Never use
__proto__in production code
Summary
Section titled “Summary”Object.create()is the cleanest way to set prototypes__proto__is deprecated but still widely supportedObject.setPrototypeOf()has performance implications- Constructor
.prototypesets the prototype for allnewinstances - Always use
Object.getPrototypeOf()for reading