I have two questions about JavaScript inheritance:
- in my code why using Object.create to inherent fail?
- 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?