Create new objects by copying an existing, fully-configured instance instead of rebuilding one from scratch.
Some objects are costly or fiddly to construct — one loaded from a database, or configured through many steps. If you need ten slightly different variants, re-running that setup ten times is wasteful when nine of them are 95% identical to an existing instance.
The object implements a `clone()` method that returns a new, independent copy of itself (a deep copy for any nested state). Callers clone an existing prototype and then adjust just the fields that differ.
`spawn()` deep-clones the template and only overrides position — every other stat is copied, not recomputed.
class Enemy {
constructor(stats) { this.stats = stats; }
clone() {
return new Enemy(structuredClone(this.stats));
}
}
const goblinTemplate = new Enemy({
hp: 30, speed: 2, loot: ["copper coin", "dagger"], x: 0, y: 0,
});
function spawn(template, x, y) {
const enemy = template.clone();
enemy.stats.x = x;
enemy.stats.y = y;
return enemy;
}
const a = spawn(goblinTemplate, 10, 5);
const b = spawn(goblinTemplate, 40, 12);
console.log(a.stats.x, b.stats.x); // 10 40
console.log(a.stats.loot === b.stats.loot); // false — independent copies