1

This question comes from my interview with a local company. I believe my answer was correct, but the interviewer said otherwise.

The question: Inherit from the Parent object Shape, create an object named Circle, then tell if the Circle instance variable is equal to the Parent object instance.

I answered 'no, they are not equal', but the interviewer said since Circle inherits from Shape, they are equal. I was very confused then.

I am curious and just wrote the following code for an 'equal' comparison, and it seems that my answer was correct. The code below is from myself:

//Parent Constructor
function Shape() {
  //this.radius = r;
}

//Child Constructor using Shape's constructor  
function Circle() {
  Shape.call(this);
}

Circle.prototype = Object.create(Shape.prototype, {
  constructor: {
    value: Circle,
    enumerable: true,
    configurable: true,
    writable: true
  }
});

var myCircle = new Circle(5);  // Child instance

var myShape = new Shape(5);    // Parent instance

console.log(myShape == myCircle);   // check for equality - result is '**false**'
TonyW
  • 18,375
  • 42
  • 110
  • 183

1 Answers1

1

You can't compare different objects instances using == as they'll have different addresses in memory. That applies in most OOP languages.

In Javascript, they could be considered equal, as Shape and Circle have the same properties obviously. So a deep comparison would return true.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85