使用Object.create与使用new的JavaScript继承

时间:2017-10-31 02:31:28

标签: javascript inheritance

我有两个关于JavaScript继承的问题:

  1. 在我的代码中为什么使用Object.create来固有失败?
  2. 如何防止第一个实例修改属性后两个实例具有相同的属性?
  3. 请将代码视为打击:

    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?
    

1 个答案:

答案 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是错误的,正如您所见 - 实例无法制作好的原型。