5

I've just run into something that really surprises me. Consider the following four functions:

function A() {
 this.q = 1;
}

function B() {
 this.q = 1;
 return this;
}

function C() {
 this.q = 1;
 return 42;
}

function D() {
 this.q = 1;
 return {};
}

and let's create objects (via new) from all of them:

console.log('a', new A());
console.log('b', new B());
console.log('c', new C());
console.log('d', new D());

This is the output:

a A { q: 1 }
b B { q: 1 }
c C { q: 1 }
d {}

First three seem to indicate that it doesn't matter what the function returns, that JS only cares about what each function does with this (which was my previous believe, btw). But the last one contradicts that.

So, what's happening here? My revised rule would be "if the function returns an Object, we keep that. Otherwise, we keep this". But I feel quite unsure about it.

LGenzelis
  • 764
  • 6
  • 14
  • 1
    read point 4 of [this description of the new operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new#Description) *Returns this if the function doesn't return an object.* - so, you've nailed it with your revised rule – Jaromanda X Oct 16 '20 at 02:33

2 Answers2

3

in JavaScript when you invoke a function without new like test() it just runs the function and it. returns whatever is being returned by the function

while when you invoke a function with new like new test() it expects the return statement to return an object else return this object.

so

function test() {
    this.q = 1
}

test(); // return undefined

new test(); // return {q:1}
Harkal
  • 1,770
  • 12
  • 28
1

When you use the new operator it creates an object.

The return value is as expected. If in the return it is an object will return that object otherwise if the return it is a function will return that function.

function A(){
    this.b = 3;
    return function(){return 4;};
}
function B(){
    this.b = 3;
    return { d:4};
}

console.log(typeof (new A())); //function
console.log(typeof (new B())); //object {d:4}

If any other value or non-existent in the return, this operator will take precedence returned as an object.

function C(){
    this.b = 3;
    return "78";
}
console.log(typeof (new C())); // object {b:3}
Lorand
  • 57
  • 1
  • 4
  • I'm selecting this as the accepted answers because it also includes the case where `typeof F` is `function` instead of `object`. @Lorand, please also include the [link from MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new#Description) provided by @Jaromanda X. – LGenzelis Oct 16 '20 at 04:27