AceDevHub
Advanced JavaScript Interview QuestionsAdvancedCode Output

JavaScript · Question 81

What happens when a bound function is called with new, and how does new.target help distinguish constructor calls?

Direct answer

If a bound function is constructable and invoked with new, the bound thisArg is ignored because construction creates a new instance; bound arguments still participate, and new.target identifies whether code is executing through construction.

bound-constructor.js
function User(name) {
  this.name = name;
}

const Bound = User.bind({ name: "ignored" }, "Ada");
const u = new Bound();

console.log(u.name);
Output
Ada

Suppose function User(name) { this.name = name; } const Bound = User.bind({ name: "ignored" }, "Ada"); const u = new Bound();. The new instance receives name === "Ada". The object passed as the bound thisArg is not used as the constructed receiver.

This follows from the difference between a normal call and a construction operation. Binding this affects calls, but a constructor call must create and initialize a fresh receiver according to construction semantics. A bound function can still pre-bind leading arguments.

  • Inside an ordinary function, new.target is undefined during a normal call.
  • During construction, new.target identifies the constructor originally invoked with new and is useful in constructor-oriented abstractions.
  • Arrow functions are not constructable and do not become constructable merely by using bind().