function sum(){
console.log(this);
}
var sum1= new sum();
console.log(sum1);
I getting sum{} sum{} as output and I am verymuch confused with this result
function sum(){
console.log(this);
}
var sum1= new sum();
console.log(sum1);
I getting sum{} sum{} as output and I am verymuch confused with this result
You're getting two outputs because the new
keyword actually executes function sum()
See the new
operator:
- Executes the constructor function with the given arguments, binding newInstance as the this context (i.e. all references to this in the constructor function now refer to newInstance).
when you create a function it creates its own internal instance (this
)
when you use new
with your function it will return this internal instance.
here's an example that illustrates that it is the same instance, which is why the console log is showing the same.
function sum(){
this.a = 1
console.log(this);
}
var sum1 = new sum();
console.log(sum1);
Note that if you don't use new
the behaviour changes. In this case, the this
is the global context and the returned value (and 2nd log result) is undefined
function sum(){
this.a = 1
console.log(this);
}
var sum1 = sum();
console.log(sum1);
to the best of my knowledge, this constructor function syntax was introduced into JS as a way to do classes, where it serves as a class constructor. Here is some additional reading that may help https://javascript.info/constructor-new#constructor-function
In JavaScript function can be used as a constructor.
Eg you can define constructor:
function Cat(color) {
this.color = color
}
and use them as
const cat = new Cat("black");
So:
In first example you have this as instance of object that you initialising. You can use this this
to create his properties. That object is returned if you use keyword new
.
so in my example you will see in constructor:
this = {} // before assignment
this = {color: "black"} // after line this.color = color
and when you will use new
you will see ready cat
{color: "black"}
in some browsers you will see also name of constructor. In my case Cat
, in your sum
.
Note that there is convention to use big letter as names of functions that are constructors. You will see syntax with class
. It is only syntactic sugar that under the hood using functions to define constructors.