Sub topic 18
Sharing Behavior with Mixins and Composition
This chapter assumes you know how Object.assign copies properties, how class methods end up on prototype, and how the prototype chain resolves lookups. It covers two topics. The first is sharing behavior without building deep class hierarchies. The second is why you should set an object's prototype when you create it rather than change it later.
Mixins: Copying Methods onto a Prototype
A JavaScript object has exactly one prototype, so a class can extend only one parent. Sometimes unrelated classes need the same behavior. A mixin is a plain object of methods that you copy onto a prototype with Object.assign.
const Serializable = {
toJSONString() {
return JSON.stringify(this);
}
};
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Object.assign(Point.prototype, Serializable);
const p = new Point(1, 2);
console.log(p.toJSONString()); // '{"x":1,"y":2}'
console.log(Object.hasOwn(p, 'toJSONString')); // falseThe method now lives on Point.prototype, so every instance shares it, and this refers to the instance that made the call. The chain stays one level deep.
Common Errors with Mixins
- Using a class as the source. Methods defined in a class body are non-enumerable, and
Object.assigncopies only enumerable own properties.Object.assign(Point.prototype, OtherClass.prototype)therefore copies nothing. - Name collisions. If two mixins define the same method, the one assigned last silently replaces the other.
- Getters are flattened.
Object.assignreads a getter once and copies the value it returned. To keep the accessor, copy it withObject.defineProperties(target, Object.getOwnPropertyDescriptors(source)).
Composition: Holding Behavior Instead of Inheriting It
With composition, an object stores a helper and delegates calls to it, so it doesn't inherit the helper's methods:
const makeLogger = (prefix) => ({
log: (msg) => `[${prefix}] ${msg}`
});
class Order {
constructor(id) {
this.id = id;
this.logger = makeLogger(`order ${id}`);
}
ship() {
return this.logger.log('shipped');
}
}
console.log(new Order(7).ship()); // "[order 7] shipped"| Approach | Behavior lives on | Best when |
|---|---|---|
| `extends` | Parent prototype | There is a true "is-a" relationship |
| Mixin | The class's own prototype | Small, stateless methods shared across classes |
| Composition | A separate helper object | The behavior has its own state or can be swapped |
Performance: Why Changing Prototypes at Runtime Is Discouraged
Engines such as V8 track each object's shape, meaning its layout of properties and its prototype. They cache property lookups based on that shape. If you call Object.setPrototypeOf or assign to __proto__ on an object that already exists, its shape changes. The engine then throws away its optimizations for that object, and it can also lose optimizations for code that has handled objects of that shape. MDN warns that this slowdown can reach beyond the single line that changed the prototype.
const base = { greet() { return 'hi'; } };
const late = {};
Object.setPrototypeOf(late, base); // discouraged: changes an existing object's shape
const early = Object.create(base); // preferred: prototype fixed at creation
console.log(late.greet(), early.greet()); // "hi hi"Exercise
A developer writes Object.assign(Point.prototype, Comparable.prototype), where Comparable is a class with a compareTo method. Calling p.compareTo then throws "not a function". Why, and how can it be fixed?
Show answer
Class methods are non-enumerable, and Object.assign copies only enumerable own properties, so nothing was copied. One fix is to define Comparable as a plain object literal. Another is to copy the descriptors with Object.defineProperties(Point.prototype, Object.getOwnPropertyDescriptors(Comparable.prototype)), but leave out the constructor property so it does not overwrite Point.prototype.constructor.
Exercise
Why is Object.create(proto) preferred over creating {} and then calling Object.setPrototypeOf(obj, proto)?
Show answer
Object.create sets the prototype when the object is created, so its shape never changes. Calling setPrototypeOf later changes the shape of an existing object, and the engine has to throw away its cached lookups and optimizations.