父对象原型继承的差异

时间:2018-01-10 18:44:54

标签: javascript object inheritance constructor prototype

我找到了3种方法来继承另一个Object-constructor的原型:

我可以全部使用这三个吗? =>如果我在Rectangle实例上测试draw()方法,它们似乎有用......

还有其他方法吗?

function Shape(shapeName){
    this.shapeName = shapeName;
}
Shape.prototype.draw = function(){
    console.log('I am a '+this.shapeName+' and I am drawing myself');
}

function Rectangle(shapeName,l,b){
    Shape.apply(this,arguments);
    this.lengte = l;
    this.breadth = b;
}

// Possibility 1 ==> Rectangle.prototype = Object.create(Shape.prototype);
// Possibility 2 ==> Object.assign(Rectangle.prototype,Shape.prototype);
// Possibility 3 ==> Rectangle.prototype = Shape.prototype;

1 个答案:

答案 0 :(得分:2)

  

我可以全部使用这三种吗?

排序,但我强烈建议您使用Possibility 1(加上constructor的结果设置Rectangle):

function Shape(shapeName){
    this.shapeName = shapeName;
}
Shape.prototype.draw = function(){
    console.log('I am a '+this.shapeName+' and I am drawing myself');
}

function Rectangle(shapeName,l,b){
    Shape.apply(this,arguments);
    this.lengte = l;
    this.breadth = b;
}

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

为什么我不会使用可能性2:它复制了所有内容,这意味着对Shape.prototype的后续修改不会被Rectangle.prototype继承。

为什么我不会使用可能性3:这意味着您无法提供Rectangle无法提供的Shape方法(因为添加到Rectangle.prototype正在添加Shape.prototype,因为它们是同一个对象),如果您triangle instanceof Rectangle也创建了Triangle并使用triangle = new Triangle()triangle,那么它会错误地class为真创建class Rectangle extends Shape { }

当您执行class Shape { constructor(shapeName) { this.shapeName = shapeName; } draw() { console.log('I am a '+this.shapeName+' and I am drawing myself'); } } class Rectangle extends Shape { constructor(shapeName, l, b){ super(shapeName); this.lengte = l; // <=== Maybe you meant "length"? this.breadth = b; } } 时,可能性1基本上也是ES2015 + ... } // the for-loop closes here. if (numberOfMeasurements == 0) return 0; // Must have at least 3 measurements in order to remove 2 of them. else if (numberOfMeasurements > 2) { temperatureMeasurementValueSum -= maxMeasuredTempValue; temperatureMeasurementValueSum -= minMeasuredTempValue; numberOfMeasurements -= 2; // Compensate removing two measurements. } // Average is sum divided by measurements. int temperatureMeasurementAverageValue = temperatureMeasurementValueSum / numberOfMeasurements; return temperatureMeasurementAverageValue; 语法的作用。事实上,我建议使用(可能使用转换器):

docker: Error response from daemon: container [id] encountered an error during CreateContainer: lost communication with compute service