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}