Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of Javascript `new` from `function` [duplicate]

Tags:

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.

like image 303
LGenzelis Avatar asked Oct 16 '20 02:10

LGenzelis


1 Answers

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}
like image 52
Harkal Avatar answered Sep 30 '22 15:09

Harkal