Behaviour of constructor function return

Viewed 56

Can someone explain this behavior or phenomenon, and what exactly is happening behind the scene?

A constructor function initialized with a new keyword is supposed to return the current object context(this) implicitly.

function User() {
  this.name = "Alice";
}

console.log( new User() );

Which is working exactly what it says.

Also explicitly returning an object is also possible with

function User() {
  this.name = "Alice";

  return { name: "Jane" };
}

console.log( new User() );

Which explicitly returning object, but when trying to return primitive value it returns what is implicitly supposed to return.

function User() {
  this.name = "Alice";

  return "Jane";
}

console.log( new User() );

Thank you in advance. Your efforts will be great input to my knowledge. 

0 Answers
Related