JavaScript
/Intermediate
Object.create()
Definition
A static method that creates a new object, using an existing object as the prototype of the newly created object.
Explain Like I'm New
If you want to create a new object that inherits from an old object, `Object.create(old)` is the cleanest, most direct way to do it. It skips constructor functions and `new` keywords entirely.
Real World Example
Creating a pure dictionary object with no built-in JavaScript methods (like `.toString`) by using `Object.create(null)` to prevent prototype pollution attacks.
Common Use Cases
- •Prototypal inheritance without Classes
- •Creating objects without the default `Object.prototype`
Interactive Example
const dogPrototype = { bark() { console.log('Woof!'); } }; // Create a new object that inherits from dogPrototype const myDog = Object.create(dogPrototype); myDog.name = 'Fido'; myDog.bark(); // 'Woof!' // Pure dictionary (No prototype) const pureMap = Object.create(null); // pureMap.toString(); // ERROR: pureMap.toString is not a function
Interview Questions
basic
- What does `Object.create()` do?
intermediate
- Why would someone use `Object.create(null)`?
advanced
- What is the second argument of `Object.create()` used for?