SlideShare une entreprise Scribd logo
1  sur  32
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

Contenu connexe

Tendances

ActionScript3 collection query API proposal
ActionScript3 collection query API proposalActionScript3 collection query API proposal
ActionScript3 collection query API proposalSlavisa Pokimica
 
The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programmingAnand Dhana
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189Mahmoud Samir Fayed
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to ProgrammingCindy Royal
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202Mahmoud Samir Fayed
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 

Tendances (20)

Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
ActionScript3 collection query API proposal
ActionScript3 collection query API proposalActionScript3 collection query API proposal
ActionScript3 collection query API proposal
 
The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210The Ring programming language version 1.9 book - Part 39 of 210
The Ring programming language version 1.9 book - Part 39 of 210
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
Javascript
JavascriptJavascript
Javascript
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 

Similaire à 11. session 11 functions and objects

JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...DEEPANSHU GUPTA
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Metaprogramming in JavaScript
Metaprogramming in JavaScriptMetaprogramming in JavaScript
Metaprogramming in JavaScriptMehdi Valikhani
 
Java script
 Java script Java script
Java scriptbosybosy
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 

Similaire à 11. session 11 functions and objects (20)

Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Actionscript
ActionscriptActionscript
Actionscript
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
java script
java scriptjava script
java script
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Javascript
JavascriptJavascript
Javascript
 
Javascripting.pptx
Javascripting.pptxJavascripting.pptx
Javascripting.pptx
 
Lodash js
Lodash jsLodash js
Lodash js
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Metaprogramming in JavaScript
Metaprogramming in JavaScriptMetaprogramming in JavaScript
Metaprogramming in JavaScript
 
Java script
 Java script Java script
Java script
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 

Plus de Phúc Đỗ

15. session 15 data binding
15. session 15   data binding15. session 15   data binding
15. session 15 data bindingPhúc Đỗ
 
14. session 14 dhtml filter
14. session 14   dhtml filter14. session 14   dhtml filter
14. session 14 dhtml filterPhúc Đỗ
 
13. session 13 introduction to dhtml
13. session 13   introduction to dhtml13. session 13   introduction to dhtml
13. session 13 introduction to dhtmlPhúc Đỗ
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objectsPhúc Đỗ
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
09. session 9 operators and statements
09. session 9   operators and statements09. session 9   operators and statements
09. session 9 operators and statementsPhúc Đỗ
 
08. session 08 intoduction to javascript
08. session 08   intoduction to javascript08. session 08   intoduction to javascript
08. session 08 intoduction to javascriptPhúc Đỗ
 
07. session 07 adv css properties
07. session 07   adv css properties07. session 07   adv css properties
07. session 07 adv css propertiesPhúc Đỗ
 
06. session 06 css color_andlayoutpropeties
06. session 06   css color_andlayoutpropeties06. session 06   css color_andlayoutpropeties
06. session 06 css color_andlayoutpropetiesPhúc Đỗ
 
05. session 05 introducing css
05. session 05   introducing css05. session 05   introducing css
05. session 05 introducing cssPhúc Đỗ
 
04. session 04 working withformsandframes
04. session 04   working withformsandframes04. session 04   working withformsandframes
04. session 04 working withformsandframesPhúc Đỗ
 
03. session 03 using lists and tables
03. session 03   using lists and tables03. session 03   using lists and tables
03. session 03 using lists and tablesPhúc Đỗ
 
02. session 02 working with html elements
02. session 02   working with html elements02. session 02   working with html elements
02. session 02 working with html elementsPhúc Đỗ
 
15. session 15 data binding
15. session 15   data binding15. session 15   data binding
15. session 15 data bindingPhúc Đỗ
 
01. session 01 introduction to html
01. session 01   introduction to html01. session 01   introduction to html
01. session 01 introduction to htmlPhúc Đỗ
 

Plus de Phúc Đỗ (15)

15. session 15 data binding
15. session 15   data binding15. session 15   data binding
15. session 15 data binding
 
14. session 14 dhtml filter
14. session 14   dhtml filter14. session 14   dhtml filter
14. session 14 dhtml filter
 
13. session 13 introduction to dhtml
13. session 13   introduction to dhtml13. session 13   introduction to dhtml
13. session 13 introduction to dhtml
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
09. session 9 operators and statements
09. session 9   operators and statements09. session 9   operators and statements
09. session 9 operators and statements
 
08. session 08 intoduction to javascript
08. session 08   intoduction to javascript08. session 08   intoduction to javascript
08. session 08 intoduction to javascript
 
07. session 07 adv css properties
07. session 07   adv css properties07. session 07   adv css properties
07. session 07 adv css properties
 
06. session 06 css color_andlayoutpropeties
06. session 06   css color_andlayoutpropeties06. session 06   css color_andlayoutpropeties
06. session 06 css color_andlayoutpropeties
 
05. session 05 introducing css
05. session 05   introducing css05. session 05   introducing css
05. session 05 introducing css
 
04. session 04 working withformsandframes
04. session 04   working withformsandframes04. session 04   working withformsandframes
04. session 04 working withformsandframes
 
03. session 03 using lists and tables
03. session 03   using lists and tables03. session 03   using lists and tables
03. session 03 using lists and tables
 
02. session 02 working with html elements
02. session 02   working with html elements02. session 02   working with html elements
02. session 02 working with html elements
 
15. session 15 data binding
15. session 15   data binding15. session 15   data binding
15. session 15 data binding
 
01. session 01 introduction to html
01. session 01   introduction to html01. session 01   introduction to html
01. session 01 introduction to html
 

Dernier

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Dernier (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

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