我有两个关于JavaScript继承的问题:
请将代码视为打击:
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?
答案 0 :(得分:1)
您需要调用父构造函数来获取初始化实例的父部分:
var Circle = function () {
Shape.call(this);
};
Circle.prototype = Object.create(Shape.prototype);
// plus the `constructor` property, but that’s not too important here
将new Shape()
分配给Circle.prototype
是错误的,正如您所见 - 实例无法制作好的原型。