JS Secrets: OOP in JavaScript Lesson 1


SUBMITTED BY: Guest

DATE: Dec. 30, 2013, 5:25 a.m.

FORMAT: JavaScript

SIZE: 1.1 kB

HITS: 1177

  1. //Let´s create a new Type
  2. function Point(x, y)
  3. {
  4. this.X = x;
  5. this.Y = y;
  6. }
  7. //Now you can use this type
  8. var myPoint new Point(10, 20);
  9. var xPosition = myPoint.X;
  10. var yPosition = myPoint.Y;
  11. //We can use this type in other types
  12. //Lets use the "Point" type in a "Line" type
  13. function Line(startPoint, endPoint)
  14. {
  15. this.StartPoint = startPoint;
  16. this.EndPoint = endPoint;
  17. this.CalculateLineLength = function() {
  18. //a² + b² = c²
  19. var aSquared = (this.EndPoint.X - this.StartPoint.X) * (this.EndPoint.X - this.StartPoint.X);
  20. var bSquared = (this.EndPoint.Y - this.StartPoint.Y) * (this.EndPoint.Y - this.StartPoint.Y);
  21. return Math.sqrt(aSquared + bSquared);
  22. }
  23. }
  24. //We need two points
  25. var myStartPoint = new Point(10, 20);
  26. var myEndPoint = new Point(30, 40);
  27. //Now we can create a "Line"
  28. var myLine = new Line(myStartPoint, myEndPoint);
  29. var lengthOfLine = myLine.CalculateLineLength();

comments powered by Disqus