Object.create(proto) makes a new object whose prototype is proto. It establishes a link rather than placing copies of the prototype’s properties on the new object. Use that link when related objects should share behavior; use an object literal when a single, self-contained object is enough. section 2.1 section 1.2
Extend a transaction
const transaction = { sender: 'luis@tjoj.com' }; const moneyTransaction = Object.create(transaction); moneyTransaction.funds = 0; moneyTransaction.sender; // 'luis@tjoj.com' Object.getPrototypeOf(moneyTransaction) === transaction; // true Here, funds belongs to moneyTransaction, while sender is found through its prototype. section 2.1
Property access checks the object first, then follows its internal [[Prototype]] link until it finds the property or reaches the end of the chain. This is why a linked object can use a property it does not declare locally. Avoid manipulating __proto__ directly; Object.create() establishes the link. section 2.1.1
Two variations matter when shaping the new object:
- Pass a second argument containing property descriptors to define properties as the object is created. Descriptor options include enumerable, writable, and configurable. section 2.1
- With constructor functions, set a derived constructor’s prototype to Object.create(Base.prototype), not Object.create(Base). This connects instances to methods shared through the base prototype. section 2.2.2
Object.create() also supports Objects Linked to Other Objects (OLOO): domain objects delegate to one another without requiring a class hierarchy. That differs from assembling behaviors into one object with mixins or Object.assign(). section 3.0
