Hey guys i have this below small programme :
function foo() {
this.x = 2;
return this;
}
var y = foo();
var g = foo();
g.x = 3;
console.log("y", y.x); // 3
console.log("g", g.x); // 3
console.log("this", this.x); //3
now all 3 console.logs print 3 , i guess the 1st console.log prints 3 because y.x is overwritten by g.x but i don't quite get why this.x prints 3 , because i have no this.x in the global scope .
My 1st question : Why does this.x print 3 ?
now if my original programmer is corrected in the following way(basically i am adding the new operator) :
function foo() {
this.x = 2;
return this;
}
var y = new foo();
var g = new foo();
g.x = 3;
console.log("y", y.x); // 2
console.log("g", g.x); // 3
console.log("this", this.x); // undefined
I get more predictable results or rather expected ones (check comments) .
What difference the new operator makes eludes me , now i browsed through SO and found this below thread :
also i saw the MDN doc's, but still i'am confused .
can somebody answer my 1st question and then also tell me Most Importantly ,how does the new operator make any difference ? in my example , make ur answer concise , just tell me the exact reason why the new operator gives me the results i want ?
Thank you .
Alexander .