0

In this JavaScript code , why the two functions when compared directly returns True while when compared using new object creation returns False?

function A() {
    return this;
}

function B() {
    return this;
}

console.log(A() === B());
console.log(new A() == new B());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Himanshu Jotwani
  • 378
  • 2
  • 16
  • Because you cannot compare two objects in javascript. There is no native method to compare two objects, you have to write it your own. – Hith Sep 11 '18 at 04:52
  • Read from here, you will know what happens I guess. https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – chintuyadavsara Sep 11 '18 at 04:56

2 Answers2

3

You should be aware that in JavaScript, this refers to the calling context or the place where the call to the function was made.

When you do

function A() {
    return this;
}

then

console.log( A() );

The calling context, for obvious reasons, is the window context and hence, this refers to window. Same is the case with B().

However, when you do new A(), you initialize a new instance of the class and, vis-a-vis, a new memory location. Since each new initialization refers to a new memory location, they never equate to true.

weirdpanda
  • 2,521
  • 1
  • 20
  • 31
2

In first case this inside the function refers to the window object. So it is basically window === window which is true

function A() {
 return this;  // this is the window object
}

function B() {
  return this; // this is window object
}

In this case new A() and new B() refers to the different memory location, so they are never equal

brk
  • 48,835
  • 10
  • 56
  • 78
  • So basically when I had created object of new function A and B, they both are stored in different location and refer to different objects?or are they just created at different location but are same objects!? – Himanshu Jotwani Sep 11 '18 at 04:57
  • 1
    They are in different locations but are of the same `class`. They have the same set of parameters and initial states, but while `A` is at say `0xAA22`, `B` might be at `0xAA21`. – weirdpanda Sep 11 '18 at 04:59
  • Okay.Got that.! – Himanshu Jotwani Sep 11 '18 at 08:44