Метод, определенный в классе, преобразуется в метод protoType, чтобы все экземпляры класса совместно использовали один и тот же метод.Версия вашего компонента с функциональным компонентом будет
function Polygon(height, width) {
this.height = height;
this.width = width;
}
function Square(sideLength){
Polygon.call(this, sideLength);
}
Square.prototype.area = function() {
return this.height * this.width;
}
Square.prototype.sideLength(newLength) {
this.height = newLength;
this.width = newLength;
}
Однако, если вы определите функцию в конструкторе класса или используете arrow functions
, они будут принадлежать экземпляру класса, например
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(sideLength) {
super(sideLength, sideLength);
this.getArea = function() {
return this.height * this.width;
}
this.sideLengthWithBind = this.sideLength.bind(this);
}
area =() =>{
return this.height * this.width;
}
sideLength(newLength) {
this.height = newLength;
this.width = newLength;
}
}
const square = new Square(5);
console.log(square);