CodePark/ problems / Implement new
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › this, call/apply/bind and prototypes

Implement new

mediumabout 20 minutes in an interview

Implement myNew(Ctor, ...args), which does what new Ctor(...args) does for an ordinary constructor function.

  1. Create a new empty object whose prototype is Ctor.prototype. If Ctor.prototype is not an object (for example it was set to null), use Object.prototype instead.
  2. Run Ctor with that object as this and the given arguments.
  3. If Ctor returns an object or a function, return that. If it returns a primitive, null or nothing, return the new object.

Rules:

  • Don't use the new keyword or Reflect.construct. You may use apply or call.
  • Ctor is always a plain function, never a class. Classes can't be called without new.
  • If Ctor is not a function, throw a TypeError.
Input: function P(n) { this.n = n; } myNew(P, 3) Output: { n: 3 }, and Object.getPrototypeOf(result) === P.prototype
Input: function F() { this.a = 1; return { b: 2 }; } myNew(F) Output: { b: 2 }a returned object replaces the new one
Input: function G() { this.a = 1; return 5; } myNew(G) Output: { a: 1 }a returned primitive is ignored