Search code examples
javascriptjavascript-objects

Strange behaviour of Javascript `new` from `function`


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.


Solution

  • 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}