0

Look at this example. Two weird constructor functions are defined here. I say weird because both have return statements and don't return (implicitly) this as normally constructor functions do.

But what is strange is that... when called with the new operator...

1) C3 returns the newly constructed this object even though it has been told to return "ggg".
2) C2 returns what it has been told to return (not the this object).

Why this difference in the behavior? What is the conceptual difference between C2 and C3?

When does a constructor function return this and when does it return what it has been told to return?

function C2() {
    this.a = 1;
    return {b: 2};
}
var c2 = new C2();
console.log(c2.a); //undefined
console.log(c2.b); //2
console.log(c2);   //{b:2}
function C3() {
    this.a = 1;
    return "ggg";
}
var c3 = new C3();
console.log(c3.a); //1
console.log(c3);   //C3 {a: 1}
FZs
  • 16,581
  • 13
  • 41
  • 50
peter.petrov
  • 38,363
  • 16
  • 94
  • 159

2 Answers2

3

Have a look at the documentation for the new operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Returns this if the function doesn't return its own object.

In case of C3 you're not returning an object (strings are primitives), so 'this' is returned.

Arian Khosravi
  • 457
  • 3
  • 11
2

Constructor functions always return objects.

The above rule can't be violated, if you try to do so (return a primitive from a constructor), the default object (this) will be returned instead.

See more information in this SO post, here, and on javascript.info.

This rule is also an invariant in Proxies, and therefore they'll even throw errors, when you try to do that:

const p=new Proxy(function(){},{
  construct(){
    return 'ggg'
  }
})

new p() //TypeError: Construct trap on proxy must return an object
FZs
  • 16,581
  • 13
  • 41
  • 50