Syncing account progress…

Back

Advanced · 12 min

Prototypes and composition

Understand inherited behavior and assemble objects from smaller capabilities.

Look up inherited properties

When a property is missing from an object, JavaScript looks along its prototype chain. Object.hasOwn() distinguishes an own property from an inherited one.

const defaults = { theme: "light" };
const settings = Object.create(defaults);
console.log(settings.theme);
console.log(Object.hasOwn(settings, "theme"));

Output

light
false

Compose a dependency

Composition lets one object use another object’s behavior without inheriting from it. Supplying a dependency makes it easy to replace in a test.

function createReporter(format) { return { report(value) { return format(value); } }; }
const reporter = createReporter(value => `Total: ${value}`);
console.log(reporter.report(8));

Output

Total: 8

Put it into practice

  1. Predict each result before running the example.
  2. Complete the coding task, then explain why your solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Override without changing defaults

Set an own theme property on settings to "dark". Keep defaults unchanged and display both values.

Practice