JavaScript Basics

Sang Shin, www.javapassion.com/ajaxcodecamp


JavaScript is the glue that makes the whole Ajax operation possible.  And having good understanding on how JavaScript works is important for writing well-functioning Ajax applications.   In this hands-on lab, you will learn various capabilities of JavaScript language by writing and running JavaScript code.


Expected duration: 90-120 minutes

Prerequisites

This hands-on lab assumes you have some basic knowledge of, or programming experience with, the following technologies.

Software Needed


Before you begin, you need to install software on your computer as mentioned here.

OS platforms you can use


Change Log


Lab Exercises



Exercise 1: JavaScript basics


The goal of this exercise is to learn how to detect the presence of JVM and the version number in the browser through JavaScript. 

(1.1) Learn when JavaScript code gets executed ("function_calling.html" )


The goal of this exercise is to understand when JavaScript code gets executed.  If the code is within a function, it gets executed only when the function gets invoked, typically as an event handler. If the code is outside of a function, it gets executed when a page that contains the code is loaded.

1. Open javascript_basics NetBeans project. 

2. Study function_calling.html.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
    <script type="text/javascript">
        // The alert message below gets executed when the page is loaded
        alert("Hello Boston! This message gets displayed when a page is loaded.");

        // If alert("Hello world!!") below had not been written within a
        // function, it would have been executed when page is loaded.
        // Since it is within a function, it will be invoked only when
        // displaymessage() function is invoked.
        function displaymessage() {
            alert("Hello World! This message is within a function and gets displayed only when the function is called.")
        }
    </script>
</head>

<body>
    <form>
        <input type="button" value="Click me!"
               onclick="displaymessage()" >
    </form>
</body>
</html>
Code-1.10: function_calling.html


3. View the function_calling.html document.


Figure-1.11: function_calling.html


Figure-1.12: JavaScript code outside a function gets executed when a page is loaded


Figure-1.13: Clicking the button invokes an event handler


Figure-1.14: JavaScript code within a function gets executed

4. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.

                                                                                                                return to top of the exercise


(1.2) Detecting the presence of JVM


1. Double-click detect_jvm.html under javascript_basics->Web Pages to open it in the source editor. (Figure-4.11 below)   Please study the code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Detect JVM</title>
</head>
<body>
    <script type="text/javascript">
        if(window.navigator.javaEnabled()){
            alert("JVM is present in your browser! Version is " + java.lang.System.getProperty("java.version"));}
        else{
            alert("JVM is NOT present in your browser!");
        }
    </script>
</body>
</html>
Code-4.11: detect_jvm.html

2. Right-click detect_jvm.html and select View.
3. Observe that the browser gets displayed with an alert message, which shows if JVM is present or not and the version number. (Figure-4.22 below)


Figure-4.22: JVM is present or not

Trouble-shooting:  The above code is working with Firefox browser but does not seem to be working with IE, or with Safari.  If you know the solution, please let me(sangshinpassion@gmail.com) know.   (According to Joh Boles - The problem is that IE does not support LiveConnect like almost all other browsers.  The only way that I know of to get the JavaScript code to work is to embed an applet and then use it to communicate the JVM version and other Java properties.  This is how we do it for our application when the IE browser is used.)



Exercise 2:DOM


The goal of this exercise is to exercise a few DOM APIs.
  1. document.write()
  2. getElementById()
  3. getElementsByName()
  4. Element collection
  5. innerHTML
  6. innerHTML with anchors


(2.1) document.write()


0. Open javascript_dom NetBeans project. 
1. Study dom_write.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
</head>
<body>

    <script type="text/javascript">
        document.write("<h1>This is written with document.write().</h1>")
    </script>

</body>
</html>

2. View dom_write.html.



                                                                                                                return to top of the exercise

(2.2) getElementById()


1. Study dom_getElementById.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
    <script type="text/javascript">
        function getElement(){
            var x=document.getElementById("myHeader")
            alert("I am a " + x.tagName + " element")
        }
    </script>
</head>

<body>
    <h1 id="myHeader" onclick="getElement()">Click  me to see what element I am!</h1>
</body>

</html>

2. View dom_getElementById.html.





                                                                                                                return to top of the exercise


(2.3) getElementsByName()


1. Study dom_getElementsByName.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
    <script type="text/javascript">
        function getElements(){
            var x=document.getElementsByName("myInput")
            alert(x.length + " elements!")
        }
    </script>
</head>

<body>
    <input name="myInput" type="text" size="20"><br />
    <input name="myInput" type="text" size="20"><br />
    <input name="myInput" type="text" size="20"><br />
    <br />
    <input type="button" onclick="getElements()" value="How many elements named 'myInput'?">
</body>

</html>

2. View dom_getElementsByName.html.





                                                                                                                return to top of the exercise

(2.4) Element collection


1. Study dom_collection.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
</head>
<body>
    <form id="Form1" name="Form1">
        Your name: <input type="text">
    </form>
    <form id="Form2" name="Form2">
        Your car: <input type="text">
    </form>

    <p>
        To access an item in a collection you can either use the number or the name of the item:
    </p>

    <script type="text/javascript">
        document.write("<p>The first form's name is: " + document.forms[0].name + "</p>")
        document.write("<p>The first form's name is: " + document.getElementById("Form1").name + "</p>")
    </script>

</body>
</html>

2. View dom_collection.html.



                                                                                                                return to top of the exercise

(2.5) innerHTML


1. Study dom_innerHTML_simple.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
    <script type="text/javascript">
        function changeGreeting() {
           mygreeting_var = document.getElementById('mygreeting_id');
           mygreeting_var.innerHTML = 'Good Day!';
        }
    </script>
</head>

<body>
    <p>Greeting of the day: <b id='mygreeting_id'>Hello!</b> </p>
    <form>
        <input type="button" value="Click me!"
               onclick="changeGreeting()" >
    </form>
</body>
</html>

2. View dom_innerHTML_simple.html.





                                                                                                                return to top of the exercise

(2.6) innerHTML with anchors


1. Study dom_innerHTML_anchor.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
</head>
<body>

    <a name="first">Text of the first anchor</a><br />
    <a name="second">Text of the second anchor</a><br />
    <a name="third">Text of the third anchor</a><br />
    <br />

    InnerHTML of the first anchor in this document:
    <script type="text/javascript">
        document.write(document.anchors[0].innerHTML)
    </script>

</body>

</html>

2. View dom_innerHTML_anchor.html.



                                                                                                                return to top of the exercise


Exercise 3: Events

In this exercise, you are going to see various examples of JavaScript code and then modify them and see the result.

  1. onclick event 1 ("onClickEvent1.html")
  2. onclick event 2 ("onClickEvent2.html")
  3. onblur event ("onBlurEvent.html")
  4. onfocus event ("onFocusEvent.html")
  5. onsubmit event ("onSubmitEvent.html)
  6. onmousedown event1 ("onMouseDownEvent1.html)
  7. onmousedown event2 ("onMouseDownEvent2.html)
  8. Explore other events on your own

(3.1)  onclick event (onClickEvent1.html)

The goal of this exercise is to learn how onclick event occurs and an event handler is  invoked as a result.

0. Open javascript_events NetBeans project. 

1. Double-click onClickEvent1.html to open it in the source editor.   Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>onClick event</title>
    <script type="text/javascript">
        // Event handler of onclick event
        function myMethod () {
            alert ("You pressed a button!");
        }
    </script>
</head>
<body>
    <INPUT TYPE="button" NAME="button" Value="Click me!" onClick="myMethod()">
</body>
</html>

2. Right-click onClickEvent1.html and select View.
3. Observe that the browser gets displayed with a button.





                                                                                                                return to top of the exercise

(3.2)  onclick event (onClickEvent2.html) with input form


1. Double-click onClickEvent2.html to open it in the source editor.   Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>onClick event</title>
    <script type="text/javascript">
        // Event handler of onclick event
        function testResults (form) {
            var TestVar = form.inputbox.value;
            alert ("You typed: " + TestVar);
        }
    </script>
</head>
<body>
    <FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
        <INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
        <!-- When the button is clicked, onclick event is generated -->
        <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
    </FORM>
</body>
</html>
Code-3.31: onClickEvent2.html

2. Right-click onClickevent2.html and select View.
3. Observe that the browser gets displayed with one input form field and a button. (Figure-3.32 below)


Figure-3.32: Display of the page

4. Type some characters, for example, Passion!, into the input form field.
5. Click Click button.  This will cause onclick event to be generated and the testResults() function will be invoked as an event handler.  (Figure-3.33 below)


Figure-3.33: Effect of the onclick event


                                                                                                                return to top of the exercise

(3.3) onblur event ("onBlurEvent.html")

The goal of this exercise is to learn how onblur event occurs, which an event handler is invoked by the event.

1. Study onBlurEvent.html.  Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title></title>
    <script type="text/javascript">
        // Event handler of the first onBlur event
        function upperCase() {
            var x=document.getElementById("fname").value;
            document.getElementById("fname").value= "Uppercase -" +
                x.toUpperCase();
        }

        // Event handler of the second onBlur event
        function lowerCase() {
            var y=document.getElementById("lname").value;
            document.getElementById("lname").value= "Lowercase -" +
                y.toLowerCase();
        }
    </script>
</head>

<body>

    Enter your first name:
    <!-- onblur event is generated when the input form field loses the focus -->
    <input type="text" id="fname" onblur="upperCase()">

    <br>

    Enter your last name:
    <!-- onblur event is generated when the input form field loses the focus -->
    <input type="text" id="lname" onblur="lowerCase()">

</body>
</html>
Code-3.21: onBlurEvent.html

2. Right-click onBlurevent.html and select View.
3. Observe that the browser gets displayed with two input form fields. 
4. Enter  your  first name, for example, Sang, into the first input form field.  (Figure-3.22 below)


Figure-3.22: Executing onBlurEvent.html

5. Press Tab key or move your mouse outside of the input form field.  This will cause onblur event to be generated and the upperCase() function will be invoked as an event handler. You should see the first name you typed is converted into upper case letters. (Figure-3.23 below)


Figure-3.23: Effect of the onblur event

6. Enter  your  last name, for example, Shin, into the second input form field.
7. Press Tab key or move your mouse outside of the input form field.  This will cause onblur event to be generated and the lowerCase() function will be invoked as an event handler. You should see the last name you typed is converted into lower case letters. (Figure-3.24 below)


Figure-3.24: Effect of the onblur event

8. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.

                                                                                                                return to top of the exercise



(3.4)  onfocus event (onFocusEvent.html)

The goal of this exercise is to learn how onfocus event occurs and an event handler is invoked as a result.  The onfocus event gets generated when an element gets a focus.

1. Double-click onFocusEvent.html to open it in the source editor. (Figure-3.41 below)   Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>onFocus event</title>
        <script type="text/javascript">
            // Event handler of onfocus event
            function upperCase() {
                document.getElementById("fname").value= "Enter your first name";
            }

            // Event handler of onfocus event
            function lowerCase() {
                document.getElementById("lname").value= "Enter your last name";
            }
        </script>
    </head>

    <body>

        Enter your first name:
        <!-- onfocus event is generated when the input form field gets a focus -->
        <input type="text" id="fname" onfocus="upperCase()">

        <br>

        Enter your last name:
        <!-- onfocus event is generated when the input form field gets a focus -->
        <input type="text" id="lname" onfocus="lowerCase()">

    </body>
</html>
Code-3.41: onFocusEvent.html

2. Right-click onFocusEvent.html and select View.
3. Observe that the browser gets displayed with two input form fields.
4. Move your mouse into the first text field and click your mouse.  You will see "Enter your first name" gets displayed.
5. Move your mouse into the second text field and click your mouse. You will see "Enter your last name" gets displayed.  (Figure-3.42 below)


Figure-3.42: Effect of onfocus event

6. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.


                                                                                                                return to top of the exercise


(3.5)  onsubmit event (onSubmitevent.html)

The goal of this exercise is to learn how onsubmit event occurs and an event handler is invoked as a result.  The event handler performs the input validation.

1. Double-click onSubmitEvent.html to open it in the source editor. (Figure-3.51 below)   Please read the comments which are highlighted in bold font. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>onSubmmit event</title>
        <script type="text/javascript">
            // This function gets called when onsubmit event occurs.
            // This function performs input form validation.
            function validate() {
                var at=document.getElementById("email").value.indexOf("@")
                var age=document.getElementById("age").value
                var fname=document.getElementById("fname").value
                submitOK="true"

                if (fname.length>10) {
                    alert("The name must be less than 10 characters")
                    submitOK="false"
                }
                if (isNaN(age)||age<1||age>100) {
                    alert("The age must be a number between 1 and 100")
                    submitOK="false"
                }
                if (at==-1) {
                    alert("Not a valid e-mail!")
                    submitOK="false"
                }
                if (submitOK=="false") {
                    return false
                }
            }
        </script>
    </head>

    <body>
        <!-- onsubmit event occurs when the submit button is clicked -->
        <form action="tryjs_submitpage.html" onsubmit="return validate()">
            Name (max 10 characters): <input type="text" id="fname" size="20"><br />
            Age (from 1 to 100): <input type="text" id="age" size="20"><br />
            E-mail: <input type="text" id="email" size="20"><br />
            <br />
            <input type="submit" value="Submit">
        </form>
    </body>

</html>
Code-3.51: onSubmitEvent.html

2. Right-click onSubmitEvent.html and select View.
3. Observe that the browser gets displayed with three input form fields and a button.
4. Type 200 in the Age (from 1 to 100) input form field.
5. Observe "The age must be a number between 1 and 100" alert message gets displayed. (Figure-3.52 below)


Figure-3.52: Input form validation through onsubmit event

6. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.


                                                                                                                return to top of the exercise

(3.6)  onmousedown event 1 (onMouseDownEvent1.html)


1. Double-click onMouseDownEvent1.html to open it in the source editor.   Please read the comments which are highlighted in bold font.  Please also see http://unixpapa.com/js/mouse.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>OnMouseDown Event 1</title>
<script type="text/javascript">
    function whichButton(event){
      // Please check  http://unixpapa.com/js/mouse.html
      if (event.which == null)
        /* IE case */
        button = (event.button < 2) ? "LEFT" :
                  ((event.button == 4) ? "MIDDLE" : "RIGHT");
      else
        /* All others */
        button = (event.which < 2) ? "LEFT" :
                  ((event.which == 2) ? "MIDDLE" : "RIGHT");
      alert ("You clicked " + button + "mouse button!");
    }
</script>
</head>

<body onmousedown="whichButton(event)">
    <p>Click in the document. An alert box will alert which mouse button you clicked.</p>
</body>

</html>

2. Right-click onMouseDownEvent1.html and select View.
3. Observe that the browser gets displayed.
4. Click any space in the browser with left button of the mouse.





5. Click any space in the browser with right button of the mouse.



6. Click any space in the browser with middle button of the mouse.



                                                                                                                return to top of the exercise


(3.7)  onsmousedown event 2 (onMouseDownEvent2.html)


1. Double-click onMouseDownEvent2.html to open it in the source editor.   Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<head>
<title>OnMouseDown Event 2</title>
<script type="text/javascript">
    function whichElement(e)
    {
        var targ
        if (!e) var e = window.event
        if (e.target) targ = e.target
        else if (e.srcElement) targ = e.srcElement
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode
        var tname
        tname=targ.tagName
        alert("You clicked on a " + tname + " element.")
    }
</script>
</head>

<body onmousedown="whichElement(event)">
    <p>Click somewhere in the document. An alert box will alert the tag name of the element you clicked on.</p>

    <h3>This is a header</h3>
    <p>This is a paragraph</p>
    <img border="0" src="ball16.gif" width="29" height="28" alt="Ball">
</body>
</html>

2. Right-click onMouseEvent2.html and select View.
3. Observe that the browser gets displayed.
4. Click any point of the This is a header string.





                                                                                                                return to top of the exercise


(3.8)  Explore other events on your own

The goal of this step is to explore other events on your own.  Please see list of events from this link.  Try to write event handlers for the events you have not tried in this exercise.



Summary

In this exercise, you learned when JavaScript code gets executed.  You also learned how various events are generated and how corresponding event handlers are invoked.

                                                                                                                 return to the top



Exercise 4: Create JavaScript objects

In this exercise, you are going to create your own JavaScript objects using the using various schemes.


(4.1) Create a direct instance of a JavaScript object

The goal of this exercise is to learn how to create an instance of JavaScript object and how to add properties and methods to it.

0. Open javascript_objects NetBeans project. 

1. Double-click createobject_directly.html to open it in the source editor. (Figure-4.11 below)   Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object directly</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(x, y){
                console.log("myMethod is invoked with " + x + " and " + y);
            }
        </script>
    </head>
    <body>
        <h1> Example of creating a JavaScript object directly</h1>
        <script type="text/javascript">

            // Create a direct instance of JavaScript object and add properties
            personObj=new Object();
            personObj.firstname="John";
            personObj.lastname="Doe";
            personObj.age=50;
            personObj.eyecolor="blue";

            // This is equivalent to println statement of Java programming language
            document.write(personObj.firstname + " is " + personObj.age + " years old.")

            // Add a method
            personObj.method1=myMethod;

            // Display the object
            console.dir(personObj);
   
            // Invoke a method
            personObj.method1();
            personObj.method1("Apple");
            personObj.method1("Apple", "Orange")
            personObj.method1(personObj.firstname, personObj.lastname)
 
        </script>
    </body>
</html>
Code-4.11: createobject_directly.html

2. Right-click createobject_directly.html and select View.
3. Observe that the browser gets displayed.




Figure-4.12: Creating a JavaScript object directly

4. Modify createobject_directly.html as shown in Code-4.13 below. The code fragments that need to be added are highlighted in bold and blue-colored font. This is to add your own direct instance of JavaScript object and add properties and methods to it.  (This code is already provided as createobject_directly_add2ndobject.html if you do not want to type.)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object directly</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(){
                alert("myMethod is invoked!");
            }
            // This is my own function that is added as a method of a JavaScript object
            function myOwnMethod(a, b, c){
                console.log("myOwnMethod is invoked: " + a + " " + b + " " + c);
                alert("myOwnMethod is invoked: " + a + " " + b + " " + c);
            }
        </script>
    </head>
    <body>
        <h1> Example of creating a JavaScript object directly</h1>
        <script type="text/javascript">

            // Create a direct instance of JavaScript object and add properties
            personObj=new Object();
            personObj.firstname="John";
            personObj.lastname="Doe";
            personObj.age=50;
            personObj.eyecolor="blue";

            // This is equivalent to println statement of Java programming language
            document.write(personObj.firstname + " is " + personObj.age + " years old.")

            // Add a method
            personObj.method1=myMethod;
    
            // Display the object
            console.dir(personObj);
    
            // Invoke a method
            personObj.method1();
            personObj.method1("Apple");
            personObj.method1("Apple", "Orange");
            personObj.method1(personObj.firstname, personObj.lastname);

            // Create my own direct instance of JavaScript object and add properties
            addressObj=new Object();
            addressObj.street="5 Dreamland";
            addressObj.city="Seoul";
            addressObj.country="Korea";
            addressObj.zip=12345;

            document.write( "  My own address is " + addressObj.street + " " + addressObj.city + " " +
                addressObj.country + " " + addressObj.zip )

            // Add a method
            addressObj.method2=myOwnMethod;

            // Display the object
            console.dir(addressObj);

            // Invoke a method
            addressObj.method2("Love", "is", "Forever!");
            
        </script>
    </body>
</html>
Code-4.13: My own direct instance of JavaScript object is added

5. Right-click File from the top-level menu and select Save.  If you skip this, the changes you made will not be reflected in the subsequent step.
6. Right-click createobject_directly.html and select View.



7. For your own exercise, please do the following tasks.
                                                                                                                return to top of the exercise


(4.2) Create a JavaScript object through a template

The goal of this exercise is to learn how to create a JavaScript object through a template.  Note that a template is just a function in which properties are defined.

1. Double-click createobject_bytemplate.html to open it in the source editor. (Figure-4.21 below)   Please read the comments which are highlighted in bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }   
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

           file:///ajaxcourse/02-AjaxJavaScript/ajaxjavascript/index_files/createobject2.png // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname
                this.lastname=lastname
                this.age=age
                this.eyecolor=eyecolor
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue")

            document.write(myFather.firstname + " is " + myFather.age + " years old.")

            // Add a method to myFather object
            myFather.method1=myMethod;
   
            // Invoke a method of myFather object
            myFather.method1(myFather.firstname);
        </script>

    </body>
</html>
Code-4.21: createobject_bytemplate.html

2. Right-click createobject_bytemplate.html and select View.
3. Observe that the browser gets displayed with properties of the JavaScript object is displayed and a method of it is also invoked. (Figure-4.22 below)


Figure-4.22: Creating a JavaScript object through a template

                                                                                                                return to top of the exercise


(4.3) Create another JavaScript object via template


Supposed you want to create the 2nd person object as shown in Code-4.31 below.  And you might expect you can invoke the newly added method from the 2nd object.  So let's do the experimentation.

1. Create 2nd object.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

            // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue");

            document.write(myFather.firstname + " is " + myFather.age + " years old.");

            // Add a method to myFather object
            myFather.method1=myMethod;
   
            // Invoke a method of myFather object
            myFather.method1(myFather.firstname);
 
            // Create another person object
            myMother=new Person("Sallie", "Lowe", 56, "brown");
   
            // Invoke the same method of myMother object.
            // This will not work because myMother object
            // does not have myMethod() defined.
            myMother.method1(myMother.firstname);
        </script>

    </body>
</html>
Code-4.31: Modified createobject_bytemplate.html

2. View the html file.

Figure-4.32: Error condition detected

The reason of the above error condition is that only the myFather object has newly added method.    In other words, the myMother object does not have newly added method.  In JavaScript, a method can be added per object basis - this is different from Java programming language.

3. Display myFather and myMother objects.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

            // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue");

            document.write(myFather.firstname + " is " + myFather.age + " years old.");

            // Display the myFather object before adding a method
            console.dir(myFather);

            // Add a method to myFather object
            myFather.method1=myMethod;

            // Display the myFather object after  adding a method
            console.dir( myFather);
   
            // Invoke a method of myFather object
            myFather.method1(myFather.firstname);
 
            // Create another Person object
            myMother=new Person("Sallie", "Lowe", 56, "brown");

            // Display the myMother object
            console.dir(myMother);
   
            // Invoke the same method of myMother object.
            // This will not work because myMother object
            // does not have myMethod() defined.
            myMother.method1(myMother.firstname);
        </script>

    </body>
</html>

4. View the change.


So question you might want to ask is "how can I modify the template so that all objects can access the newly added method or properties?".  Well, the answer is "You will have to redefine the template".  So let's do just that.

5. Redefine the template. (Later on you will learn how to use JavaScript's prototype capability to do the same.)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

            // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue");

            document.write(myFather.firstname + " is " + myFather.age + " years old.");

            // Display the myFather object before adding a method
            console.dir(myFather);

            // Add a method to myFather object
            myFather.method1=myMethod;

            // Display the myFather object after  adding a method
            console.dir( myFather);
   
            // Invoke a method of myFather object
            myFather.method1(myFather.firstname);

            // Redefine the template
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;

                //Add a method
                this.method1=myMethod;
            }
 
            // Create another Person object
            myMother=new Person("Sallie", "Lowe", 56, "brown");

            // Display the myMother object
            console.dir(myMother);
   
            // Invoke the same method of myMother object.
            // This will work now because myMother object
            // does have myMethod() defined.
            myMother.method1(myMother.firstname);
        </script>

    </body>
</html>
Code-4.33: Modified createobject_bytemplate.html

4. View the change.

Figure-4.34: Effect of modifying the template

                                                                                                                return to top of the exercise


(4.4) Create JavaScript object as Hash literal


1. Study createobject_asHashLiteral.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Example of creating a JavaScript object as a Hash Literal</title>
    <script type="text/javascript">
        // This is a function that is added as a method of a JavaScript object
        function myMethod(x){
            console.log("myMethod is invoked with " + x);
        }
    </script>
</head>
<body>
    <h1> Example of creating a JavaScript object as a Hash Literal</h1>
    <script type="text/javascript">

    // Create hash literal JavaScript object and assign it
    // to personObj
    var personObj = {
            firstname: "John",
            lastname: "Doe",
            age: 50,
            method1: myMethod,
            tellYourage: function() {
                  console.log("The age is " + this.age );
            },
            tellSomething: function(something) {
                  console.log(something);
            }
     }
     personObj.method1("Apple");
     personObj.tellYourage();
     personObj.tellSomething("Life is good!");

    </script>
</body>
</html>

2. View createobject_asHashLiteral.html.



                                                                                                                return to top of the exercise


(4.5) Experiment on how to add functions to a JavaScript object


1. View createobject_function_properties.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Create JavaScript object directly</title>
    <script type="text/javascript">
        // This is a function that is added as a method of a JavaScript object
        function myMethod(x){
            alert("myMethod is invoked with " + x);
        }
    </script>
</head>
<body>
    <h1> Example of how function property is added to JavaScript object</h1>
    <script type="text/javascript">

    var personObj = {
            firstname: "John",
            lastname: "Doe",
            age: 50,
            x: myMethod,
            y: myMethod()             // Alert message - "myMethod is invoked with undefined"
     }
     personObj.x("Apple");       // Alert message - "myMethod is invoked with Apple"
     personObj.y("Apple");       // Nothing

    </script>
</body>
</html>



                                                                                                                return to top of the exercise

Summary

In this exercise, you have learned how to create your own JavaScript objects and how to access the properties and methods of them.


                                                                                                                          return to the top


Exercise 5: Prototype


In this exercise, you are going to learn how to use JavaScript's prototype capability.
    1. Add a new property to a template using "prototype"
    2. Add a new property to a template without using "prototype"
    3. Add a new method to all objects (of a template) through "prototype"

(5.1) Add a new property to a template without using "prototype"

0. Open javascript_objects_prototype NetBeans project. 

1. Study createobject_bytemplate_addnewproperty_with_prototype.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

            // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue");

            // Add a new property to Person template using "prototype"
            Person.prototype.myJSONObject1 = { "first_name": "Sang",
                                   "last_name": "Shin",
                                   "Age": 99}

            // Create another Person object
            myMother=new Person("Sallie", "Lowe", 56, "brown");

            // Display objects
            console.dir(Person);
            console.dir(myFather);
            console.dir(myMother);

            // Display the field
            console.log("My mother's son's last name is " );
            console.log("My Father's son's last name is " + myFather.myJSONObject1.last_name);
        </script>

    </body>
</html>

2. View createobject_bytemplate_addnewproperty_with_prototype.html.


                                                                                                                return to top of the exercise


(5.2) Add a new property to a template without using "prototype"


1. Study createobject_bytemplate_addnewproperty_without_prototype.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

            // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue");

            // Add a new property to Person template without using "prototype"
            Person.myJSONObject1 = { "first_name": "Sang",
                             "last_name": "Shin",
                             "Age": 99}

            // Create another Person object
            myMother=new Person("Sallie", "Lowe", 56, "brown");

            // Display objects
            console.dir(Person);
            console.dir(myFather);
            console.dir(myMother);

            // Display the field
            console.log("My mother's son is " + myMother.myJSONObject1);
            console.log("My Father's son is " + myFather.myJSONObject1);
        </script>

    </body>
</html>

2. View createobject_bytemplate_addnewproperty_without_prototype.html.


                                                                                                                return to top of the exercise


(5.3) Add a new method to all objects (of a template) through "prototype"


1. Study createobject_bytemplate_add2ndobject_prototype.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>Create JavaScript object through a template</title>
        <script type="text/javascript">
            // This is a function that is added as a method of a JavaScript object
            function myMethod(name){
                console.log("myMethod is invoked! The name is " + name);
            }
        </script>
    </head>

    <body>
        <h1> Example of creating a JavaScript object through a template</h1>
        <script type="text/javascript">

            // Define a template.  Note that a template is just a function.
            // The properties are needed to be initialized with this.
            function Person(firstname,lastname,age,eyecolor){
                this.firstname=firstname;
                this.lastname=lastname;
                this.age=age;
                this.eyecolor=eyecolor;
            }

            // Create a Person object
            myFather=new Person("John","Doe",50,"blue");

            // Display myFather object
            console.dir(myFather);

            // Add a method to Person class
            Person.prototype.method1=myMethod;

            // Display myFather object
            console.dir(myFather);

            // Invoke a method of myFather object
            myFather.method1(myFather.firstname);
 
            // Create another Person object
            myMother=new Person("Sallie", "Lowe", 56, "brown");

            // Display myMother object
            console.dir(myMother);

            // Invoke the same method of myMother object.
            // This will work now because myMother object
            // does have myMethod() defined.
            myMother.method1(myMother.firstname);
        </script>

    </body>
</html>

2. View createobject_bytemplate_add2ndobject_prototype.html.



                                                                                                                return to top of the exercise




Summary

In this exercise, you have learned how to create JavaScript file as a separate and how to access them from your JavaScript code.


                                                                                                                return to the top




Homework exercise (for people who are taking Sang Shin's "Ajax and Web 2.0 online course") - 4 hours


The goal of this homework exercise is to let you exercise the things you learned so far from the presentation and hands-on lab, and at the same time to let you explore other features of JavaScript that have not been covered in the presentation and hands-on lab but using the excellent learning material from w3schools.com.

1. Write myOwnJavascript.html as following.  (You can just add a new HTML file to the javascript_basics project if you are using NetBeans.)
2. Write myOwnJavaScript.js as a separate file
3. Do the JavaScript Quiz Test from w3schools.com.  (No need to submit anything on this)

4. Send the following files to ajaxhomework@javapassion.com with Subject as AJAXHomework-ajaxjavascript.

                                                                                                                                                return to the top