1

I have two questions about JavaScript inheritance:

  1. in my code why using Object.create to inherent fail?
  2. how to prevent two instances have same property after the first instance modifying the property?

Please see the code as blow:

var Shape = function () {
    this.nums = [1,2,3,4,5];
}

Shape.prototype.getNum = function() {
    return this.nums;
}
var Circle = function(){};

//Inheritance
// Circle.prototype = Object.create(Shape.prototype); //Uncaught TypeError: Cannot read property 'push' of undefined
Circle.prototype = new Shape();


var circle1 = new Circle();
circle1.nums.push(6);
console.log(circle1.getNum()); // 1, 2, 3, 4, 5, 6

var circle2 = new Circle();
console.log(circle2.getNum()); // 1, 2, 3, 4, 5, 6

// console.log(circle2.getNum()); should only show 1,2,3,4,5 
// how to make it circle2 right?
Ry-
  • 218,210
  • 55
  • 464
  • 476
Zichen Ma
  • 907
  • 3
  • 14
  • 30
  • *"after the first instance modifying the property"* - Note that that's not what your code does, it mutates the array the the property refers to, it doesn't modify the property itself. (Because of the way object references work you could also say `var x = circle1.nums; x.push(7)` and that too would add a value to the same array.) Anyway, your `.nums` property is on the `Circle`'s prototype, so multiple instances of `Circle` are supposed to share it - that's how prototype-based inheritance works. – nnnnnn Oct 31 '17 at 03:00
  • Thank you. I understood better know – Zichen Ma Oct 31 '17 at 04:15

1 Answers1

1

You need to call the parent constructor to get the parent part of the instance initialized:

var Circle = function () {
    Shape.call(this);
};

Circle.prototype = Object.create(Shape.prototype);
// plus the `constructor` property, but that’s not too important here

Assigning new Shape() to Circle.prototype is wrong, as you’ve seen – instances don’t make good prototypes.

Ry-
  • 218,210
  • 55
  • 464
  • 476