I read in on one of the blogs that when we use a new keyword , a proto object would be created and "this" would be set to proto object.
If that's what it said, it was wrong.
If the new operator is used when calling a function, the function's this parameter is set to a new Object created as if by new Object()
. This object has its internal [[Prototype]]
set to the constructor's public prototype object.
It also causes the function to return this new object (and instance of the constructor) if no other object is returned by a return statement, so:
function test() {
this.x = 10;
}
var obj = new test();
Creates a new object with a public x property with value 10
and internal [[Prototoype]]
property that references test.prototype. A reference to this new object is assigned to obj.
So, when I just call var obj = test(); , will the "this" be set to proto object or will the proto object not created at all in this scenario?
You mean like:
var obj = test();
In this case, test is called without setting its this, so it will default to the global object (or be undefined in strict mode), so that:
this.x = 10;
creates an x property of the global object (if it didn't already exist) and assigns it the value of 10
. This effectively creates a global variable, with subtle differences to one created using a variable declaration in the global execution context.