Question

Assume we have two functions like the followings :

function a(){ this.x = 5; return {z:20};} 
function b(){ this.x = 5; return 30;} 

now if you run these lines everything seems to be reasonable:

a(); //output : {z:20} 
b(); //output : 30; 

but if you run them as object constructor :

new a() //output : Object {z:20} 
new b() //output : b {x:5} 

I don't understand if the new constructor should always return an object, why is the behavior different? Does JavaScript watch the return type? If the return type is an object so returns it directly and if not it returns the initiated instance?

I think if it is a constructor, so it should ignore the return type always and returs the initiated object. I think this behavior makes JavaScript too complex. Is there something else here that I don't get?

Was it helpful?

Solution

I don't understand if the new constructor should always return an object, why is the behavior different? Does JavaScript watch the return type? If the return type is an object so returns it directly and if not it returns the initiated instance?

Basically yes. If the return value of the function is not an object, the new operator returns this (the new object) instead (actually it's the internal [[Construct]] method which does that).

I think if it is a constructor, so it should ignore the return type always and returs the initiated object. I think this behavior makes JavaScript too complex. Is there something else here that I don't get?

That's really more a subjective opinion. The advantage is that the constructor can decide to return a different value, which makes it more flexible. On the other side I'd argue that it's more common to not return a value than the other way round.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top