Objects, prototypes and classes · mid
What new does, and constructor functions
new F(args) creates a fresh object whose [[Prototype]] is F.prototype, runs F with this set to that object, and returns it — unless F returns its own object, which then replaces it.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- The steps: create a plain object; link its prototype to F.prototype (if that is an object); call F with this = the new object; return the new object unless F returned an object (a returned primitive is ignored).
- Calling a constructor function without new: in sloppy mode this is globalThis, so properties leak onto the global object; in strict mode it throws when it sets a property. Classes always throw without new.
- new.target tells a function whether it was called with new.
- Constructor functions put shared methods on F.prototype; F.prototype.constructor points back to F.
- myNew(F, ...args) = Object.create(F.prototype) + F.apply(obj, args) + the object-return check.
- Bound functions can be called with new (the bound this is ignored). Arrow functions and object methods can't be constructors.
The red pen
Common traps: mistake → fix
Mistake: new always returns this
Fix: an object returned by the constructor wins.
Mistake: Returning a primitive from a constructor replaces the instance
Fix: primitives are ignored.
Easy to hard
Questions interviewers ask, easy to hard
- What does new do, step by step?
- What is the difference between Person(), new Person() and a class Person?
- Implement myNew.
- What happens if the constructor returns an object? A number?
- How do you make a function work with or without new?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.