Page 158 - DCAP202_Fundamentals of Web Programming
P. 158

Unit 13: Building Object of JavaScript




          13.1 Using JavaScript as a Scientific Calculator                                      Notes

          JavaScript’s Math object provides advanced arithmetic and trigonometric functions, expanding
          on JavaScript’s basic arithmetic operators (plus, minus, multiply, divide). The Math object in
          JavaScript is borrowed from Java. In fact, the implementation of the Math object in JavaScript
          closely parallels the Math class in Java, except that the  JavaScript Math object offers  fewer
          methods.
          JavaScript’s Math object properties are treated as constants. In fact, the property names are in all
          upper-case, following the usual convention of capitalizing variable constants. These properties
          return often-used values, including pi and the square root of 2. The Math methods are used in
          mathematical and trigonometric  calculations.




             Notes  Handy Math-object methods include ceilings, floor,paw, exp (exponent), max, min,
             round, and random. (Random is only available when  using the X Window  platform,
             however.)
          The Math object is static, so you don’t need to create a new Math object in order to use it. To access
          the properties and method of the Math object, you merely specify the Math object, along with
          the method or property.


                 Example: To return the value of pi, you use:
                                         var pi = Math. PI;
          Similarly, to use a math method you provide the name of the method, along with the parameters
          to use.


                 Example: To round the value of pi, you’d use:
                                       var pi = Math.PI;
                              var pieAreRound = Math.round(pi); // displays
          JavaScript does not recognize the keywords PI and round all by themselves. Exception: you may
          use with statement to associate the names of methods and properties with the Math object.



             Did u know?  This technique is a handy space-saver when you must use several.
          The previous example can be written as
          With  (Math)
          {
          var  pi  =  PI;  Notes
          var  pieAreRound  =  round(pi);
          alert  (pieAreRound)
          }
          13.1.1 JavaScript Objects for a Date


          The Date object is useful when you want to display a date or use a timestamp in some sort of
          calculation. In Java, you can either make a Date object by supplying the date of your choice, or




                                           LOVELY PROFESSIONAL UNIVERSITY                                   151
   153   154   155   156   157   158   159   160   161   162   163