Rectangles and Circles¶
All the interesting stuff is in the JavaScript, so open up a JavaScript console and look at the console.log output.
Again, these are simple classes, without inheritance
class Rect {
// c1 and c2 are any two corners
constructor(c1,c2) {
// UL is upper left, LR is lower right
this.ulx = Math.min(c1.x, c2.x);
this.uly = Math.max(c1.y, c2.y);
this.lrx = Math.max(c1.x, c2.x);
this.lry = Math.min(c1.y, c2.y);
}
area () {
let width = this.lrx - this.ulx;
let height = this.uly - this.lry;
return width * height;
}
}
var origin = {x: 0, y: 0};
var p1 = {x: 10, y: 20};
var r1 = new Rect(origin, p1);
console.log(r1);
console.log("area is "+r1.area());
class Circ {
constructor(center, radius) {
this.center = center;
this.radius = radius;
}
area () {
let radius = this.radius;
return Math.PI * radius * radius;
}
}
var c1 = new Circ( origin, 10);
console.log(c1);
console.log("area of c1 is "+c1.area());
var objs = [ r1, c1, new Rect(p1, {x: 5, y: 15}), new Circ( p1, 100) ];
objs.forEach( function (obj, i) {
console.log(i+" area of "+obj+" is "+obj.area());
});