У меня есть быстрый вопрос. Позвольте мне рассказать вам о процессе. Я хочу создать фигуры в холсте в js. Мои фигуры - это треугольник, прямоугольник и квадрат. Квадратный объект расширен от прямоугольника и использует конструктор прямоугольника.
Я могу печатать прямоугольник легко, но печатать квадрат не так просто, как есть. Код будет полезен.
function Rectangle(p, firstsideoflenght, secondsideoflenght) {
this.p1 = p
this.firstsideoflenght = firstsideoflenght
this.secondsideoflenght = secondsideoflenght
this.p2 = new Point(p.x + firstsideoflenght, p.y);
this.p3 = new Point(p.x, p.y + secondsideoflenght);
this.p4 = new Point(p.x + firstsideoflenght, p.y + secondsideoflenght);
this.getArea = function () {
return firstsideoflenght * secondsideoflenght;
}
}
мои точки - p1 p2 p3 и p4. Я использую это, чтобы нарисовать, как вы знаете.
function Square(p, sidelength) {
Rectangle.call(p, sidelength, sidelength);
}
Square.js использует конструктор прямоугольников.
У меня есть main.js для выполнения моих кодов.
/*var topLeft = new Point(200, 200);
var myRectangle = new Rectangle(topLeft, 50, 100);
myRectangle.points = [myRectangle.p1, myRectangle.p2, myRectangle.p4, myRectangle.p3];
myRectangle.init();
myRectangle.draw();*/
var topLeft = new Point(130, 130);
var mySquare = new Square(topLeft, 50);
debugger
mySquare.points = [mySquare.p1, mySquare.p2, mySquare.p3, mySquare.p4];
mySquare.init();
mySquare.draw();
На данный момент я не могу достичь этих точек с помощью квадрата. Консоль говорит, что mySquare.p1 не определен.
Благодарю. Надеюсь, я смогу хорошо себя зарекомендовать.
Вы должны передать контекст в качестве первого аргумента Function.prototype.call
function Square(p, sidelength) {
Rectangle.call(this, p, sidelength, sidelength);
function Point(x, y) {
this.x = x;
this.y = y;
}
function Rectangle(p, firstsideoflenght, secondsideoflenght) {
this.p1 = p
this.firstsideoflenght = firstsideoflenght
this.secondsideoflenght = secondsideoflenght
this.p2 = new Point(p.x + firstsideoflenght, p.y);
this.p3 = new Point(p.x, p.y + secondsideoflenght);
this.p4 = new Point(p.x + firstsideoflenght, p.y + secondsideoflenght);
this.getArea = function () {
return firstsideoflenght * secondsideoflenght;
}
}
function Square(p, sidelength) {
Rectangle.call(this, p, sidelength, sidelength);
}
var topLeft = new Point(130, 130);
var mySquare = new Square(topLeft, 50);
console.log(mySquare.p1, mySquare.p2, mySquare.p3, mySquare.p4)