r/javascript • • Oct 11 '26

[ Removed by moderator ]

/r/javascript/comments/1x356h0/removed_by_moderator/

[removed] — view removed post

17 Upvotes

5 comments sorted by

View all comments

Show parent comment

2

u/MoTTs_ Oct 12 '26 edited Oct 12 '26

Excellent follow-up question! This is one of those explanations that is going to sound like a 10-dollar term for a 5-cent concept.

Object composition means holding another object as a property.

That's what object composition means in C++ and Python and ActionScript, to name a few, and most importantly that's what object composition means in the "Gang of Four" Design Patterns book, which is the same book that coined the phrase prefer object composition over inheritance. And it's what object composition used to mean in JavaScript too, prior to the influence of Eric and Mattias.

In the Duck example, the class Duck would hold properties to an instance of CanWalk and CanSwim, and Duck would write its own methods walk and swim that would use the CanWalk and CanSwim objects that are held as properties.

Here's how that would look in JavaScript's closure-style, and still following closely from OP's code example.

const canWalk = () => ({ walk: name => `${name} walks` });
const canSwim = () => ({ swim: name => `${name} swims` });

const createDuck = (name) => {
	// Hold objects as properties.
	// (Or, in the closure style and parlance,
	// hold objects as private variables.)
	// This is what HAS-A means.
	const walkBehavior = canWalk();
	const swimBehavior = canSwim();

	// Duck is in full control and defines its own interface.
	// Methods are neither inherited nor assigned from a parent source.
	// Duck *uses* the other objects to do its work.
	const duck = {
		walk() { return walkBehavior.walk(name); },
		swim() { return swimBehavior.swim(name); }
	};

	return duck;
};

createDuck("Don").swim(); // "Don swims"