1

I have a quick question. Let me tell you about the process. I want to create shapes into canvas in js. My shapes are triangle,rectangle and square. Square object extended from rectangle and uses rectangle's constructor.

I can print rectangle easily but printing square is not easy as it is. Code will be helpful.

RECTANGLE.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;
}
}

my points are p1 p2 p3 and p4. Im using that points to draw as you know.

SQUARE.js

function Square(p, sidelength) {
Rectangle.call(p, sidelength, sidelength);
}

Square.js uses rectangles constructor.

I have a main.js to execute my codes.

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();

At this point, i can't reach that points with using square. Console says mySquare.p1 undefined.

Thanks. I hope i could express myself well.

1 Answer 1

1

You need to pass context as the first argument to 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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.