I was just playing with JavaScript and creating constructors, and I came across this perplexing code.
var foo = function(){
this.x = 1;
return function(){
return this.x;
}
}
var x = new foo();
console.log(x);
I executed the following for this:
console.log(x); // The given output is expected for this line of code
console.log(x());
console.log(x()());
console.log(x()()());
All of the above gave me the same output as following:
function (){
return this.x;
}
Can somebody explain what is happening in the above code. I could not give a proper title for this question. Sorry about that.
Note: I'm aware of constructors in JS. And the above code was just out of curiosity.