Skip to the page

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.

The 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

  1. What does new do, step by step?
  2. What is the difference between Person(), new Person() and a class Person?
  3. Implement myNew.
  4. What happens if the constructor returns an object? A number?
  5. How do you make a function work with or without new?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview