0

javascript class

Can I somehow shorten this code? var result = document.getElementById("result"); function Circle(pi, r) { this.pi = pi; this.r = r; this.print1 = function() { } } function Triangle(a, b, c, h) { this.a = a; this.b = b; this.c = c; this.h = h; } function Rectangle(x, y) { this.x = x; this.y = y; } Circle.prototype.calcArea = function() { result.innerHTML += "Pole tego koła wynosi: " + this.pi * this.r * this.r + "cm2" + "<br>"; } Circle.prototype.calcCircuit = function() { result.innerHTML += "Obwód tego koła wynosi: " + 2 * this.pi * this.r + "<hr>"; } Triangle.prototype.calcArea = function() { result.innerHTML += "Pole tego trójkata wynosi: " + this.a * this.h / 2 + "cm2" + "<br>"; } Triangle.prototype.calcCircuit = function() { result.innerHTML += "Obwód tego trójkąta wynosi: " + (this.a + this.b + this.c) + "<hr>"; } Rectangle.prototype.calcArea = function() { result.innerHTML += "Pole tego prostokąta wynosi: " + this.x * this.y + "cm2" + "<br>"; } Rectangle.prototype.calcCircuit = function() { result.innerHTML += "Obwód tego prostokąta wynosi: " + 2 * (this.x + this.y) + "<hr>"; } var circle = new Circle(3.14, 5); var triangle = new Triangle(3, 4, 5, 6); var rectangle = new Rectangle(6, 7); circle.calcArea(); circle.calcCircuit(); triangle.calcArea(

31st Dec 2016, 10:28 AM
Robert Koronny
Robert Koronny - avatar
3 Respuestas
+ 3
Hmm, maybe not shorter, but cleaner? Whenever we notice patterns in our code we should try and abstract them away. Six times we output to the screen - three "Obwód" things, and three "Pole" things. The only thing differing is the name ("koła", "trójkata", "prostokąta") and the fomulas. Also, pi is already available as Math.PI! So what I would do: - Seperate out the name - Seperate out the writing to result Like this: http://lpaste.net/4433155223048945664
31st Dec 2016, 12:19 PM
Schindlabua
Schindlabua - avatar
0
thank you, great job!!!
31st Dec 2016, 3:02 PM
Robert Koronny
Robert Koronny - avatar
0
another question ... how can round this result?
5th Jan 2017, 4:54 PM
Robert Koronny
Robert Koronny - avatar