Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.4 — Constructor Functions and new
JavaScript · Example 2 of 3

What new does, rebuilt by hand

Returning an object from a constructor throws the new object away. Returning a number is ignored.

A constructor is an ordinary function meant to be called with new; new creates a fresh object, links it to the function's prototype property, runs the function with this set to that object, and gives you the object back.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a constructor Book(title, pages) with a prototype method isLong() that returns true when pages are over 300. Create two books and print isLong() for each.

02

Write myNew(Fn, ...args) without looking, and test it with a constructor Pet(name) that has a prototype method hello().

03

Add a new.target guard to Book that throws a clear error (Book must be called with new) instead of fixing the call, and show what happens when someone calls Book("x", 10).

Explain it without notes

01

What exactly happens when you call a function with new?

02

Why should methods go on Fn.prototype instead of being created inside the constructor?

03

How does instanceof work, and when can it give a surprising answer?

04

What happens if you forget new, and how can you protect against it?

What new does, rebuilt by hand

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Tea: Rs 30 | Coffee: Rs 50
true
{ y: 2 } ReturnsNumber { x: 1 }