2. JavaScript OO Programming

About this Tutorial

Objectives

Delegates will learn to develop applications using HTML5/CSS3 and JS. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial HTML5 Web Applications
  • Develop Websites that may use web sockets, animations and geolocation

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of HTML/CSS and JavaScript will also find the content beneficial.

Prerequisites

No previous experience in web programming is required. But any experience you do have in programming will help. Also no experience in browser IDE’s is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Looking at Events

What is JavaScript?

    • JavaScript is an Object Oriented Programming (OOP) language
      • An OOP language allows you to define your own objects and make your own variable types
      • An object has properties and methods
    • Properties are the values associated with an object
      • Accessed via object.property syntax
      • Or via object[“property“] syntax if you prefer
      • E.g. Use the length property of the String object to return the number of characters in a string
        <script type="text/javascript">
        var txt="llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch";
        document.write(txt + " has a length of " + txt.length + "<br/>");
        document.write(txt + " still has length " + txt["length"] + "<br/>");
        </script>
    • Methods
      • Methods are the actions that can be performed on objects
      • E.g. Use the toUpperCase() method of the String object to display a text in uppercase letters
        <script type="text/javascript">
        var txt="llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch";
        document.write(txt + " in uppercase is " + txt.toUpperCase());
        </script>

Lab 1: Getting started with objects

Lab 1: Getting started with objects
  1. JavaScript Objects
    • JavaScript has several built-in objects
      • E.g. String, Date, Array, RegExp, etc.
    • In addition to these built-in objects, you can also create your own –
      • An object is just a special kind of data, with a collection of properties and methods.
    • ObjectJs

  2. Scenario
    • An example of an object might be Employee
    • The Employee object has properties:
      • Properties are the values associated with the object.
      • E.g. name, age, salary.
      • All employees have these properties, but the values of the properties will differ from one employee to another.
    • The Employee object also has methods:
      • Methods are the actions that can be performed on objects
      • E.g. changeName(), payRise().
  3. Creating a New Object
    • Here’s one way to create a new object – Use the syntax new Object()
      var employee1 = new Object();
    • Here’s another way to create an object – Use empty {} to represent the object
      var employee1 = {};
  4. Defining Properties
    • You can add properties to an object – Use the syntax objName.propertyName = value
      employee1.name = "John Smith";
      employee1.age = 21;
      employee1.salary = 10000;
  5. Defining Methods
    • You can also add methods to an object – Use the syntax objName.methodName = existingFunction
      function payRise(amount) {
       this.salary += amount;      // Note, this means "the current object"
       return this.salary;
      }
      ...
      employee1.payRise = payRise;
  6. Invoking Methods:
    • To invoke methods on an objet use the syntax objName.methodName(params)
      var newSal = employee1.payRise(1000);
      document.write("New salary for employee1 is " + newSal);
    • See Complete Example – SimpleObjectsSyntax.html
    • View code file.
Lab
  1. For the Labs in this tutorial we will be using the product manager project again (ProductManager.sln) the version you will be working on will be in a folder named initial and the fully working one in a folder called final.
  2. Take a look at the following files to remind yourself how the application works (this is the same as the solution code to the previous lab):
    • MainPage.htm is the fully-complete Web page for this Web application.
    • ProductSuggestionsFunctions.js contains all the initial JavaScript code for this Web application. At the moment, it uses a string to represent each product. In this lab, you’ll refactor this code to use a Product object instead.
  3. Run the Web application and familiarize yourself with its capabilities
    ObjectJs
  4. Defining a Product object – The best way to define a new object is by implementing a constructor function.Therefore, open ProductSuggestionsFunctions.js and define a constructor function as follows:
    • Declare a global variable named Product.
    • Assign the Product variable a constructor function. The constructor function should take 4 parameters representing the following product-related info:
      • description
      • user’s email
      • recommended retail price
      • estimated sales per year
    • Inside the function body, assign the following properties to “this” object:
      • description
      • email
      • price
      • sales
      • ts (this is the timestamp of creation assign the current date/time)
    • At the end you should end up with something that looks similar to this:
      var Product = function (description, email, price, sales) {
        this.description = description;
        this.email = email;
        this.price = price;
        this.sales = sales;
        this.ts = new Date();
      };

Lab 2: Using property-setter syntax

Lab 2: Using property-setter syntax
  1. General Syntax
    • JavaScript supports the following syntax for setting properties on an object:
      var objectName = {
       property1: value1,
       property2: value2,
       ...
      };
  2. Defining Properties:
    • The following example shows how to set properties on a new object:
      • Creates an object
      • Adds properties to the object
      • Sets values for each property
      • var employee1 = {
         name: "John Smith",
         age: 21,
         salary: 10000
        };

  3. Defining Methods:
    • You can use the property-setter syntax to define a method for an object
      • Set a property and assign it an existing function
        function payRise(amount) {
         this.salary += amount;      
         return this.salary;
        }
        function displayDetails() {
         alert(this.name + " is " + this.age + " and earns " + this.salary);
        }
        var employee1 = {
         name: "John Smith",
         age: 21,
         salary: 10000,
         payRise: payRise,
         displayDetails: displayDetails
        };
    • You can also define an object’s methods inline, as part of the object definition:
      • Implement the function inline via the syntax function(){…}
      • Within the function, the this keyword refers to the target object
        var employee2 = {
         name: "Mary Jones",
         age: 42,
         salary: 20000,
         payRise: function(amount) {
          this.salary += amount;      
          return this.salary;
         },
         displayDetails: function() {
          alert(this.name + " is " + this.age + " and earns " + this.salary);
         }
        };
    • For Complete Example see PropertySetters.html
    • View code file.

Lab 3: Using constructors and prototypes

Lab 3: Using constructors and prototypes
  1. Defining and Using a Constructor
    • In JavaScript, a constructor is a function that assigns properties to “this” object:
      var Account = function (id, name) {
       this.id = id;
       this.name = name;
       this.balance = 0;
       this.numTransactions = 0;
       return this;
      };
    • You can use a constructor function to create a new object and initialize its values
      var acc1 = new Account(1, "Emily");
      ...
      var acc2 = new Account(2, "Tom");
      ...
    • prototypeJs

  2. What is a Prototype?
    • Every JavaScript object has a property named prototype:
      • Acts as a default place to define methods for an object
    • This is how prototype works:
      • When you invoke a method on an object.
      • If JavaScript can’t find the method on the actual object.
      • It looks on the object’s prototype to see if the method is defined there instead
    • You can use prototypes to extend an existing object:
      • Add methods or properties
      • Can be used to implement inheritance see later in this chapter for details
    • For example on how to define a prototype
      Account.prototype = {
       deposit: function(amount) {
        this.balance += amount;
        this.numTransactions++;
       },
       withdraw: function(amount) {
        this.balance -= amount;
        this.numTransactions++;
       },
       displayDetails: function() {
        alert(this.id + ", " +
           this.name + " balance $" +
           this.balance + " (" +
           this.numTransactions + " transactions)");
       }
      };
    • And how to use a prototype – For complete example see ConstructorsAndPrototypes.html
    • View code file.
    • var acc1 = new Account(1, "Emily");
      acc1.deposit(1000);
      acc1.deposit(2000);
      acc1.withdraw(400);
      acc1.displayDetails();
      var acc2 = new Account(2, "Tom");
      acc2.deposit(3000);
      acc2.deposit(1000);
      acc2.displayDetails();

Lab
  1. Adding methods to the Product object – Now it’s time to add functionality to Product. To do this, set the Product.prototype property so that it includes a format function as follows:
    • The function should create a formatted string that contains the product’s:
      • description
      • email
      • price
      • sales
    • The function should then append the formatted timestamp – For above and this you can get most of this code from the existing doAdd() function you might need to make some tweaks
    • The function should then return this concatenated text and will look similar to this:
        format: function () {
          var str = this.description.toUpperCase().big().bold().fontcolor("orange") + "<br/>"
                      + "Suggested by " + this.email + "<br/>"
                      + " " + this.price + " [projected sales " + this.sales + "]<br/>";
          var tsStr = this.ts.getDate() + "/" + (this.ts.getMonth() + 1) + "/" + this.ts.getFullYear() + ", " +
                pad(this.ts.getHours()) + ":" + pad(this.ts.getMinutes()) + ":" + pad(this.ts.getSeconds());
          str += tsStr.fontcolor("blue");
          return str;
        },

Lab 4: Implementing inheritance in JavaScript

Lab 4: Implementing inheritance in JavaScript
  1. Why use inheritance?
    • Inheritance is an important concept in OO languages
      • Allows you to define a new object based on an existing object
      • You just specify how the new object differs from the existing one
    • Potential benefits of inheritance:
      • Code reuse
      • Consistency
      • Ability to define new variations based on existing objects
    • InheritanceJs

  2. Defining a Base Object:
    • Consider the following base object – Defines common properties and methods required by all kinds of “sprites” in an HTML animation Web page
      // Constructor, defines properties for a Sprite object.
      var Sprite = function(name) {
       this.name = name;
       this.x = 0;    
       this.y = 0;    
       this.v = 0;    
       return this;
      };
    • Define the methods for the base object such as move and accelerate

      // Prototype, defines methods for a Sprite object.
      Sprite.prototype = {
       move: function(dx, dy) {
        this.x += dx;
        this.y += dy;
       },
       accelerate: function(dv) {
        this.v += dv;
       }
      };
  3. Defining a Derived Object
    • To define a derived object:
      • Implement a constructor that calls the base-class constructor
      • This will cause the derived object to inherit all the properties defined in the base object
    • Example:
      • Here’s a Ball object
      • It inherits all the properties of the Sprite object
        // Constructor, defines properties for a Ball object.
        var Ball = function(name, radius, elasticity) {
         // Call the Sprite (i.e. base-object) constructor.
         Sprite.call(this, name);
         // Define additional Ball-specific properties.
         this.radius = radius;
         this.elasticity = elasticity;
         return this;
        };
  4. Defining Methods in a Derived Object
    • First inherit methods from the base object
      • Set the derived object’s prototype property to a new instance of the base object
        Ball.prototype = new Sprite();
    • Then add new methods to the derived object as needed
      • Add them to the prototype for the derived object
        Ball.prototype.inflate = function(dr) {
         this.radius += dr;
        };
        Ball.prototype.getSurfaceArea = function() {
         return Math.PI * this.radius * this.radius * 4.0;
        };
        Ball.prototype.getVolume = function() {
         return Math.PI * this.radius * this.radius * this.radius * 4.0 / 3.0;
        };
Lab
  1. Refactoring the Web application to use the Product object – In this exercise, you’ll refactor your code so that it uses the Product object.
    • First, refactor doAdd() so that it creates a Product object to contain the information entered by the user, and then add the Product object (rather than a formatted string) in the global allProducts array. This simply means changing the formatted string to the code below and then pushing the product itself.
      // Create a new Product object with the data garnered from the form.
      var product = new Product(description, email, price, sales);
      // Add this Product object to the global array of all products.
      allProducts.push(product);
    • Next, refactor displayProducts() so that it makes use of the Product object’s format() method to return a formatted string representation of each product, ready to be displayed on the form. To do this we use a for loop to run through each product in products and add them to an unordered list:
      // Create a string containing an HTML unordered list.
      var str = "<ul>";
      for (var i in products) {
       str += "<li>" + products[i].format() + "</li>";
      }
      str += "</ul>";
    • Finally, refactor doSort() so that it sorts the array of Product objects by description.
      • The default behavior of the array sort() function is to call toString() on each object in the array, to compare items lexicographically. Therefore, a simple solution would be for you to implement a toString() method in the Product prototype that just returned the product’s description.
      • Another (more flexible approach) is to supply a function to the array sort() function, to tell it how to compare two Product objects explicitly. Here’s what we suggest for your doSort() function:
          allProducts.sort(function (p1, p2) {
            if (p1.description < p2.description)       return -1;     else if (p1.description > p2.description)
              return +1;
            else
              return 0;
          });
          displayProducts(allProducts, "allProductsList");
  2. Run the Web application. Add several product suggestions and verify the Web page displays them correctly. Also verify that the Sort and Reverse buttons still work correctly.

 

Well done. You have completed the tutorial in the HTML5/CSS3/JS course. The next tutorial is

3. Looking at Events


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top