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.