我找到了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;
答案 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