0

When I explicitly return an object (or something that derives from Object) from a constructor (new) it ignores the newly created object instance and returns what I told it to, but when I return a primitive data type like a number or a string it ignores my explicit return and returns the new instance. Does anyone know why this is? I dont think its a bug in the JS engine because I tried it in firefox, safari, and chrome and it all behaves the same.

function Fun1(){
  return {Hats: 5};
}
Fun1(); // => {Hats: 5};
new Fun1(); // => {Hats: 5};

function Fun2(){
  return 5;
}
Fun2(); // => 5;
new Fun2(); // => Fun2 {};
TheContrarian
  • 166
  • 1
  • 3
  • 3
    Because a function called as a constructor must return an object (see the [`[[Construct]]`](http://es5.github.io/#x13.2.2) internal method). – RobG May 03 '14 at 22:02
  • if you run b.constructor(), you will get 5.. – Hawk May 03 '14 at 22:05
  • http://stackoverflow.com/questions/1978049/what-values-can-a-constructor-return-to-avoid-returning-this – TGH May 03 '14 at 22:05

0 Answers0