Guarding against a missing new
Point repairs a missing new. Unsafe has no guard, so in strict mode this is undefined and the script stops. A wrapper object like new Boolean(false) is truthy.
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.
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.
Write myNew(Fn, ...args) without looking, and test it with a constructor Pet(name) that has a prototype method hello().
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
What exactly happens when you call a function with new?
Why should methods go on Fn.prototype instead of being created inside the constructor?
How does instanceof work, and when can it give a surprising answer?
What happens if you forget new, and how can you protect against it?
Preview
Console
Nothing logged yet.Expected console output
Point { x: 1, y: 2 }
Point { x: 3, y: 4 }
arrow has prototype? false
object true
Uncaught TypeError: Cannot set properties of undefined (setting 'name')