SlideShare a Scribd company logo
Functions and Objects
      Session 11
Objectives
   User-defined functions.
   User-defined objects.
   JavaScript objects.
What is a function?
   A function is an independent reusable block of
    code that performs certain operations on variables
    and expressions to fulfill a specific task.
   In JavaScript, a function is similar to method, but
    there is a little difference between them. A
    method is always associated with an object and is
    executed by referencing that object. But a
    function is executed independently.
   In JavaScript, a function is always created under
    the Script element.
Function Definition
   Syntax:
function <functionName>([paraList])
{
   //Body of function
}
-   <functionName>: comply with identifier naming convention.
-   [paraList]:is optional. If there are many parameters, separated by commas.
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <script language="javascript" type="text/javascript">
      function add(num1, num2)
      {
          var result = num1 + num2;
         document.write("Result of " + num1 + " + " + num2 + " = " + result);
      }
   </script>
   </head>
   <body onLoad="add(5, 17)">
   </body>
</html>
Invoking functions
   You can invoke or call a unction to execute it in the browser.
   You can call a function from another function in JavaScript. The
    function that calls another function is called calling function,
    whereas, the called function is referred to as the called function.
   Syntax to calling a function
<functionName>([paralist]);
Ways of passing parameters
   There are two ways of passing parameters to a function
    namely, pass by value and pass by reference.
   Passing by value refers to passing variables as
    parameters to a function. The called function do not
    change the values of the parameters passed to it from
    the calling method. Because, each parameter occupies
    different memory locations.
   Passing by reference, the called can change the value of
    parameters passed to it from the calling method.
Calling by value- Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Calling function by value</title>
   <script language="javascript" type="text/javascript">
         function swap(num1, num2)
         {
            var temp = num1;   num1 = num2;   num2 = temp;
            document.write("Called method: num1="+num1+ " and num2=" + num2);
         }

        function calculate()
        {
           var num1=10, num2=20;
           swap(num1, num2);      //Invoking the swap mathod
           document.write("<br>Calling method: num1 = " + num1 + " and num=
                 " + num2);
        }
   </script>
   </head>
   <body onLoad="calculate()">
   </body>
</html>
Calling by reference - Demo
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>Calling function by reference</title>
   <script language="javascript" type="text/javascript">
         function modify(names)
         {
                  names[0] = "Thanh Hung";
         }
         function initialize()
         {
                  var names = new Array("James","Helene","John");
                  document.write("Before invoking method:<br>");
                  for(var i=0; i<names.length; i++)
                           document.write(names[i] + " - ");
                  modify(names);            //Invoking method
                  document.write("<Br>After invoking method:<br>");
                  for(var i=0; i<names.length; i++)
                           document.write(names[i] + " - ");
         }
   </script>
   </head>
   <body onLoad="initialize()“></body></html>
return statement
   JavaScript allows you to send the result back to the
    calling function by using return statement.
   Syntax:
        return <expression>
Returning an array
   You can use the return statement to return a collection
    of values stored in arrays.
   Syntax:
        return <ArrayObject>
Object definition
   In JavaScript, object is a collection of properties and methods.
    Properties specify the characteristics or attributes of an object, while
    methods identify the behavior of an object.
   For example, car is an object in the real world.
        Car properties: brand, model, color, number, …
        Car methods: run, reverse, brake, …
   In JavaScript, objects have their own properties and methods.
    JavaScript provides built-in objects and allows creating user-defined
    objects.
   Pre-defined objects are those objects that are already defined and you
    just need to use their properties and methods to perform a specific
    task. (e.g. Array object).
Creating user-defined objects
   Can create custom objects to store related data in a script.
    Example: to store the doctor details such as name, age,
    hospital name …, can to create doctor object.
   There are two methods to create a custom object:
     By using Object object: This is known as the direct method.
    var <objectName> = new Object();
     By defining a template and initializing it with the new keyword.

      There are two steps to create an object by using this method.
            First: Declare the object type by using the constructor.
            Second: Specify the object of declared object type by using the new keyword.
    function <objectType>(paraList)
    {
       //Body specifying properties and methods
    }
By using Object object - Demo
By defining template - Demo
Creating properties
   You can define properties of a custom object by specifying
    the object name followed by a period and property name.
   To get value to property of custom object:
        <objectName>.<property>
   To set value to property of custom object:
        <objectName>.<property> = <value>
Creating properties in template
   You can specify the properties in the template, if the template
    method is implemented to create a custom object.
   In the constructor to create the custom object, you want to
    declare properties with the same names as that of parameters
    to specify meaningful names of properties.
   Finally, you can set and get the value o properties easily.
Creating methods
There are two ways to define methods o custom object.
 First way: for the custom object created by Object object.
<objectName>.<MethodName> = function([paraList])
{
   //Body of function
}
Creating methods in a template
   Second way: creating methods in a template. You can create the custom
    method with the following steps:
    1.   Define a method function that implements a functionality.
    2.  Define a constructor function where the custom method is assigned
        the name of the method function.
    3.  Create an object.
    4.  Invoke the custom method, which in turn, will invoke the method
        function.
String object
   Strings in JavaScript are set of characters that are surrounded
    by single or double quotes.
   The built-in String object represents such a set of characters
    and allows you to perform different text operations on them.
   You can perform these text operations by creating an instance
    (custom object) the String object.
   Syntax:
    var <objectName> = new String(“strings”);
   Example:
    var name = new String(“John Smith”);
Properties and methods of String object
   Properties:
      length: retrieves the number of characters in a string.

   Methods:
      chartAt(): retrieves a character from a particular position
       within a string.
      concat(): concatenates two strings.
      indexOf(): retrieves the position at which the specified string
       value first occurred in the string.
      lastIndexOf(): retrieves the position at which the specified
       string value last occurred in the string.
      match(): matches a regular expression with the string and
       replaces it with a new string.
      search(): searches for a match where the string is in the

       same format as specified by a regular expression.
Properties and methods of String object
   Methods:
       split(): divides the string into substrings and defines an array
        of these substrings.
       substring(): retrieves a part of a string between the specified
        positions of a string.
       toLowerCase(): specifies the lowercase display of the string.
       toUpperCase(): specifies the uppercase display of the string.
       charCodeAt(): retrieves the Unicode of character located at a
        particular position.
       fromCharCode(): retrieves the string representation of the
        specified set of Unicode values.
       substr(): retrieves the particular number of a characters in a
        string from the specified index until the specified length.
String object - Demo
Math object
   The Math object allows you to perform mathematical operations
    on numeric values. It is a pre-defined object that provides static
    properties and methods to perform mathematical operations.
   Properties:
      E: retrieves the Euler’s constant that is approximately 2.7183.
      PI: retrieves the value of pi that is approximately 3.142.

   Syntax to use Math properties:
     var <variableName> = Math.<Property>
   Example:
     var Pi = Math.PI;
Methods of Math object
   Methods:
       abs(): retrieves the absolute value of a numeric value.
       ceil(): retrieves the integer greater than or equal to the
        given numeric value.
       floor(): retrieves the integer less than or equal to the given
        numeric value.
       exp(): returns E exponent of parameter value.
       max(): retrieves the greatest value from the list of values
        passed as arguments.
       min(): retrieves the most lesser value from the list of values
        passed as arguments.
       pow(): calculates and retrieves the value of a raised to the
        power of b.
Methods of Math object
   Methods:
       random(): retrieves a random value between 0 to 1.
       round(): is used to round the number.
       sqrt(): retrieves the square root of a numeric value.
Math object - Demo
Date object
   The Date object allows you to define and manipulate the
    date and time values programmatically.
   The Date object calculates dates in milliseconds from 01
    January, 1970.
   You can specify date and time by creating an instance of the
    Date object. This is done by instantiating the Date object
    with the new keyword.
   Syntax:
     var <objectName> = new Date();
   Example:
     var today = new Date();
Methods of Date object
   Methods:
       getDate(): retrieves the day of month (1-31).
       getDay(): retrieves the day of week (0-6).
       getMonth(): retrieves the month of year (0-11).
       getFullYear(): retrieves the year.
       getHours():retrieves the hour value between 0 and 23.
       getMinutes(): retrieves the minute value (0-59).
       getSeconds(): retrieves the second value (0-59).
       getTime(): retrieves a numeric value, which indicates the
        time passed in milliseconds since midnight 01/01/1070.
       setTime(): specifies the time based on the given
        milliseconds, which have been elapsed since 01/01/1970.
Date object - Demo
with statement
   You need to use the object name every time when you
    want to access its properties and methods. This affects the
    readability of the code. To overcome this drawback, you
    can use the with statement.
   The with statement allows you to remove the object
    reference for each JavaScript statement. You can reference
    directly properties and methods of the object after using
    with statement with object.
   Syntax:
    With(<objectName>)
    {
      //statements
    }
with statement - Demo
Summary
   Javascript function is a block of code that can
    be resused later in the script.
   Javascript Object is a set of properties and
    methods, which allow store and manipulate
    information about specific entity.
   Can create custom functions, custom objects
    with custom properties and methods.


                                  Building Dynamic Websites/Session 1/ 32 of 16

More Related Content

What's hot (20)

PPTX
Python: Basic Inheritance
Damian T. Gordon
 
PPTX
ActionScript3 collection query API proposal
Slavisa Pokimica
 
PDF
The Ring programming language version 1.9 book - Part 39 of 210
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.2 book - Part 37 of 181
Mahmoud Samir Fayed
 
PPT
Prototype Utility Methods(1)
mussawir20
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPT
Spsl v unit - final
Sasidhar Kothuru
 
DOCX
descriptive programming
Anand Dhana
 
PDF
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
PDF
Uncommon Design Patterns
Stefano Fago
 
PDF
The Ring programming language version 1.6 book - Part 40 of 189
Mahmoud Samir Fayed
 
PDF
Core concepts-javascript
Prajwala Manchikatla
 
PPTX
Javascript Basics
msemenistyi
 
PDF
Handout - Introduction to Programming
Cindy Royal
 
PDF
The Ring programming language version 1.8 book - Part 36 of 202
Mahmoud Samir Fayed
 
PDF
Swift for TensorFlow - CoreML Personalization
Jacopo Mangiavacchi
 
PPT
Javascript
mussawir20
 
PPT
Advanced Javascript
Adieu
 
PDF
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Python: Basic Inheritance
Damian T. Gordon
 
ActionScript3 collection query API proposal
Slavisa Pokimica
 
The Ring programming language version 1.9 book - Part 39 of 210
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 37 of 181
Mahmoud Samir Fayed
 
Prototype Utility Methods(1)
mussawir20
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Spsl v unit - final
Sasidhar Kothuru
 
descriptive programming
Anand Dhana
 
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Uncommon Design Patterns
Stefano Fago
 
The Ring programming language version 1.6 book - Part 40 of 189
Mahmoud Samir Fayed
 
Core concepts-javascript
Prajwala Manchikatla
 
Javascript Basics
msemenistyi
 
Handout - Introduction to Programming
Cindy Royal
 
The Ring programming language version 1.8 book - Part 36 of 202
Mahmoud Samir Fayed
 
Swift for TensorFlow - CoreML Personalization
Jacopo Mangiavacchi
 
Javascript
mussawir20
 
Advanced Javascript
Adieu
 
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 

Similar to 11. session 11 functions and objects (20)

PPT
Spsl vi unit final
Sasidhar Kothuru
 
PPT
Actionscript
saad_darwish
 
PDF
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
PPTX
java script
monikadeshmane
 
PPSX
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
PPT
Java: Objects and Object References
Tareq Hasan
 
DOCX
WD programs descriptions.docx
anjani pavan kumar
 
PPTX
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
PPTX
JavaScript Arrays and its types .pptx
Ramakrishna Reddy Bijjam
 
PDF
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
DEEPANSHU GUPTA
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PPTX
Java script advance-auroskills (2)
BoneyGawande
 
PPTX
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
PPSX
Oop features java presentationshow
ilias ahmed
 
PDF
Javascript
20261A05H0SRIKAKULAS
 
PPTX
Javascripting.pptx
Vinod Srivastava
 
PDF
Lodash js
LearningTech
 
PPS
Advance Java
Vidyacenter
 
PDF
Metaprogramming in JavaScript
Mehdi Valikhani
 
PPTX
Data and information about anatical subject
epfoportal69
 
Spsl vi unit final
Sasidhar Kothuru
 
Actionscript
saad_darwish
 
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
java script
monikadeshmane
 
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
Java: Objects and Object References
Tareq Hasan
 
WD programs descriptions.docx
anjani pavan kumar
 
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
JavaScript Arrays and its types .pptx
Ramakrishna Reddy Bijjam
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
DEEPANSHU GUPTA
 
JavaScript - An Introduction
Manvendra Singh
 
Java script advance-auroskills (2)
BoneyGawande
 
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Oop features java presentationshow
ilias ahmed
 
Javascripting.pptx
Vinod Srivastava
 
Lodash js
LearningTech
 
Advance Java
Vidyacenter
 
Metaprogramming in JavaScript
Mehdi Valikhani
 
Data and information about anatical subject
epfoportal69
 
Ad

More from Phúc Đỗ (15)

PPTX
15. session 15 data binding
Phúc Đỗ
 
PPTX
14. session 14 dhtml filter
Phúc Đỗ
 
PPTX
13. session 13 introduction to dhtml
Phúc Đỗ
 
PPTX
12. session 12 java script objects
Phúc Đỗ
 
PPTX
10. session 10 loops and arrays
Phúc Đỗ
 
PPTX
09. session 9 operators and statements
Phúc Đỗ
 
PPT
08. session 08 intoduction to javascript
Phúc Đỗ
 
PPT
07. session 07 adv css properties
Phúc Đỗ
 
PPTX
06. session 06 css color_andlayoutpropeties
Phúc Đỗ
 
PPTX
05. session 05 introducing css
Phúc Đỗ
 
PPTX
04. session 04 working withformsandframes
Phúc Đỗ
 
PPT
03. session 03 using lists and tables
Phúc Đỗ
 
PPT
02. session 02 working with html elements
Phúc Đỗ
 
PPTX
15. session 15 data binding
Phúc Đỗ
 
PPT
01. session 01 introduction to html
Phúc Đỗ
 
15. session 15 data binding
Phúc Đỗ
 
14. session 14 dhtml filter
Phúc Đỗ
 
13. session 13 introduction to dhtml
Phúc Đỗ
 
12. session 12 java script objects
Phúc Đỗ
 
10. session 10 loops and arrays
Phúc Đỗ
 
09. session 9 operators and statements
Phúc Đỗ
 
08. session 08 intoduction to javascript
Phúc Đỗ
 
07. session 07 adv css properties
Phúc Đỗ
 
06. session 06 css color_andlayoutpropeties
Phúc Đỗ
 
05. session 05 introducing css
Phúc Đỗ
 
04. session 04 working withformsandframes
Phúc Đỗ
 
03. session 03 using lists and tables
Phúc Đỗ
 
02. session 02 working with html elements
Phúc Đỗ
 
15. session 15 data binding
Phúc Đỗ
 
01. session 01 introduction to html
Phúc Đỗ
 
Ad

Recently uploaded (20)

PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 

11. session 11 functions and objects

  • 2. Objectives  User-defined functions.  User-defined objects.  JavaScript objects.
  • 3. What is a function?  A function is an independent reusable block of code that performs certain operations on variables and expressions to fulfill a specific task.  In JavaScript, a function is similar to method, but there is a little difference between them. A method is always associated with an object and is executed by referencing that object. But a function is executed independently.  In JavaScript, a function is always created under the Script element.
  • 4. Function Definition  Syntax: function <functionName>([paraList]) { //Body of function } - <functionName>: comply with identifier naming convention. - [paraList]:is optional. If there are many parameters, separated by commas. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script language="javascript" type="text/javascript"> function add(num1, num2) { var result = num1 + num2; document.write("Result of " + num1 + " + " + num2 + " = " + result); } </script> </head> <body onLoad="add(5, 17)"> </body> </html>
  • 5. Invoking functions  You can invoke or call a unction to execute it in the browser.  You can call a function from another function in JavaScript. The function that calls another function is called calling function, whereas, the called function is referred to as the called function.  Syntax to calling a function <functionName>([paralist]);
  • 6. Ways of passing parameters  There are two ways of passing parameters to a function namely, pass by value and pass by reference.  Passing by value refers to passing variables as parameters to a function. The called function do not change the values of the parameters passed to it from the calling method. Because, each parameter occupies different memory locations.  Passing by reference, the called can change the value of parameters passed to it from the calling method.
  • 7. Calling by value- Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Calling function by value</title> <script language="javascript" type="text/javascript"> function swap(num1, num2) { var temp = num1; num1 = num2; num2 = temp; document.write("Called method: num1="+num1+ " and num2=" + num2); } function calculate() { var num1=10, num2=20; swap(num1, num2); //Invoking the swap mathod document.write("<br>Calling method: num1 = " + num1 + " and num= " + num2); } </script> </head> <body onLoad="calculate()"> </body> </html>
  • 8. Calling by reference - Demo <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Calling function by reference</title> <script language="javascript" type="text/javascript"> function modify(names) { names[0] = "Thanh Hung"; } function initialize() { var names = new Array("James","Helene","John"); document.write("Before invoking method:<br>"); for(var i=0; i<names.length; i++) document.write(names[i] + " - "); modify(names); //Invoking method document.write("<Br>After invoking method:<br>"); for(var i=0; i<names.length; i++) document.write(names[i] + " - "); } </script> </head> <body onLoad="initialize()“></body></html>
  • 9. return statement  JavaScript allows you to send the result back to the calling function by using return statement.  Syntax: return <expression>
  • 10. Returning an array  You can use the return statement to return a collection of values stored in arrays.  Syntax: return <ArrayObject>
  • 11. Object definition  In JavaScript, object is a collection of properties and methods. Properties specify the characteristics or attributes of an object, while methods identify the behavior of an object.  For example, car is an object in the real world.  Car properties: brand, model, color, number, …  Car methods: run, reverse, brake, …  In JavaScript, objects have their own properties and methods. JavaScript provides built-in objects and allows creating user-defined objects.  Pre-defined objects are those objects that are already defined and you just need to use their properties and methods to perform a specific task. (e.g. Array object).
  • 12. Creating user-defined objects  Can create custom objects to store related data in a script. Example: to store the doctor details such as name, age, hospital name …, can to create doctor object.  There are two methods to create a custom object:  By using Object object: This is known as the direct method. var <objectName> = new Object();  By defining a template and initializing it with the new keyword. There are two steps to create an object by using this method.  First: Declare the object type by using the constructor.  Second: Specify the object of declared object type by using the new keyword. function <objectType>(paraList) { //Body specifying properties and methods }
  • 13. By using Object object - Demo
  • 15. Creating properties  You can define properties of a custom object by specifying the object name followed by a period and property name.  To get value to property of custom object: <objectName>.<property>  To set value to property of custom object: <objectName>.<property> = <value>
  • 16. Creating properties in template  You can specify the properties in the template, if the template method is implemented to create a custom object.  In the constructor to create the custom object, you want to declare properties with the same names as that of parameters to specify meaningful names of properties.  Finally, you can set and get the value o properties easily.
  • 17. Creating methods There are two ways to define methods o custom object.  First way: for the custom object created by Object object. <objectName>.<MethodName> = function([paraList]) { //Body of function }
  • 18. Creating methods in a template  Second way: creating methods in a template. You can create the custom method with the following steps: 1. Define a method function that implements a functionality. 2. Define a constructor function where the custom method is assigned the name of the method function. 3. Create an object. 4. Invoke the custom method, which in turn, will invoke the method function.
  • 19. String object  Strings in JavaScript are set of characters that are surrounded by single or double quotes.  The built-in String object represents such a set of characters and allows you to perform different text operations on them.  You can perform these text operations by creating an instance (custom object) the String object.  Syntax: var <objectName> = new String(“strings”);  Example: var name = new String(“John Smith”);
  • 20. Properties and methods of String object  Properties:  length: retrieves the number of characters in a string.  Methods:  chartAt(): retrieves a character from a particular position within a string.  concat(): concatenates two strings.  indexOf(): retrieves the position at which the specified string value first occurred in the string.  lastIndexOf(): retrieves the position at which the specified string value last occurred in the string.  match(): matches a regular expression with the string and replaces it with a new string.  search(): searches for a match where the string is in the same format as specified by a regular expression.
  • 21. Properties and methods of String object  Methods:  split(): divides the string into substrings and defines an array of these substrings.  substring(): retrieves a part of a string between the specified positions of a string.  toLowerCase(): specifies the lowercase display of the string.  toUpperCase(): specifies the uppercase display of the string.  charCodeAt(): retrieves the Unicode of character located at a particular position.  fromCharCode(): retrieves the string representation of the specified set of Unicode values.  substr(): retrieves the particular number of a characters in a string from the specified index until the specified length.
  • 23. Math object  The Math object allows you to perform mathematical operations on numeric values. It is a pre-defined object that provides static properties and methods to perform mathematical operations.  Properties:  E: retrieves the Euler’s constant that is approximately 2.7183.  PI: retrieves the value of pi that is approximately 3.142.  Syntax to use Math properties: var <variableName> = Math.<Property>  Example: var Pi = Math.PI;
  • 24. Methods of Math object  Methods:  abs(): retrieves the absolute value of a numeric value.  ceil(): retrieves the integer greater than or equal to the given numeric value.  floor(): retrieves the integer less than or equal to the given numeric value.  exp(): returns E exponent of parameter value.  max(): retrieves the greatest value from the list of values passed as arguments.  min(): retrieves the most lesser value from the list of values passed as arguments.  pow(): calculates and retrieves the value of a raised to the power of b.
  • 25. Methods of Math object  Methods:  random(): retrieves a random value between 0 to 1.  round(): is used to round the number.  sqrt(): retrieves the square root of a numeric value.
  • 27. Date object  The Date object allows you to define and manipulate the date and time values programmatically.  The Date object calculates dates in milliseconds from 01 January, 1970.  You can specify date and time by creating an instance of the Date object. This is done by instantiating the Date object with the new keyword.  Syntax: var <objectName> = new Date();  Example: var today = new Date();
  • 28. Methods of Date object  Methods:  getDate(): retrieves the day of month (1-31).  getDay(): retrieves the day of week (0-6).  getMonth(): retrieves the month of year (0-11).  getFullYear(): retrieves the year.  getHours():retrieves the hour value between 0 and 23.  getMinutes(): retrieves the minute value (0-59).  getSeconds(): retrieves the second value (0-59).  getTime(): retrieves a numeric value, which indicates the time passed in milliseconds since midnight 01/01/1070.  setTime(): specifies the time based on the given milliseconds, which have been elapsed since 01/01/1970.
  • 30. with statement  You need to use the object name every time when you want to access its properties and methods. This affects the readability of the code. To overcome this drawback, you can use the with statement.  The with statement allows you to remove the object reference for each JavaScript statement. You can reference directly properties and methods of the object after using with statement with object.  Syntax: With(<objectName>) { //statements }
  • 32. Summary  Javascript function is a block of code that can be resused later in the script.  Javascript Object is a set of properties and methods, which allow store and manipulate information about specific entity.  Can create custom functions, custom objects with custom properties and methods. Building Dynamic Websites/Session 1/ 32 of 16