JS SEcrets: OOP in JavaScript Lesson 1


SUBMITTED BY: Guest

DATE: Dec. 29, 2013, 11:32 p.m.

FORMAT: JavaScript

SIZE: 1.1 kB

HITS: 1286

  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. //We need two points
  24. var myStartPoint = new Point(10, 20);
  25. var myEndPoint = new Point(30, 40);
  26. //Now we can create a Line
  27. var myLine = new Line(myStartPoint, myEndPoint);
  28. var lengthOfLine = myLine.CalculateLineLength();

comments powered by Disqus