JavaScript: Objects, Methods and Functions

 

 

Functions

  • There are NO return types for functions. Also parameters are not declared to have any type (see variables)
  • Functions are defined by themselfs like in C/C++
  • To declare a function you use the special keywork function.
  • Examples

    function printHello() {

              document.write("Hello");

    }

    function addSquare(x,y) {

               return (x*y*x*y);

    }

  • You can assign functions to variables to pass them around:
    • var sin = Math.sin;     //note Math is a predefined Javascript Class and sin is
  •                                  //a method/function of it

    document.write("the Sin(2.0) =" + sin(2.0));

 

Classes/Objects and Methods

  • Unlike in C/C++ and Java there is not a very structured way in which you create Classes.

    The Steps

    1. Instead you define a function that serves as a constructor. It assigns values using the special keywork this (same meaning as in Java...meaning this class).
    2. Then separately you can create functions that can serve ("be applied") as methods to an instance of the class in question. This assumes, these methods/functions access information the class has access to.

      Hence,

      classes = constructor function and methods

      methods = associated functions

    Example

     

    <Script Language="JavaScript">

    //Constructor for Car class

    function Car(m, y) {

             this.make = m;

            this.year = y;

            this.PrintCarInfo = PrintCarInfo;

    }

    //Functon to serve as method to Car class

    function PrintCarInfo() {

             document.write("Make" + this.make);

             document.write("Year" + this.year);

    }

    </SCRIPT>

     

     

     

    //Later on use the code above to create an instance

    //of Car class and invoke PrintCarInfo as its method

    <SCRIPT Language="JavaScript">

    //create instance of Car class defined above

    myCar = new Car("Ford", 2002);

    //now print info about the object

    myCar.PrintCarInfo();

    </SCRIPT>

     

     

  • NOTE line in red above (this.PrintCarInfo = PrintCarInfo) associates the function PrintCarInfo as a method of the Car class
  • Built-in Objects/Classes and their Methods:
    • Every built-in object has its own associated functions. These are called the object's methods. Here is the form for executing a method: object.method(arguments); The specific structure is predefined as to which method you are using.
    • Here are a couple methods and their syntax:
      • document.write(text) - the text can be any value which will be taken and written in your current document's source.
      • window.open(URL, name) - this method opens a new window, takes it to the given URL, and gives it a name.
  •  

  • Dynamically Adding variables/fields to an Object:
    • you can add variables to an object that aren't defined in the constructor anytime you want (EXTERMELY UNSTRUCTURED) by simply having a statement of the general form:

      Object.NewVarName = Value_you_want_to_assign_to_it;

      Example from the code above:

      myCar.model ="Mustang";

  • How to access All of the variables/fields in an Object (especially when you may not know what they are...because of the possibility of dynamically adding)
    • Use the "for/in" statement (something we don't have in Java, C/C++ but, like the foreach statement in Perl):

    for(fieldName in ObjectName) {

             .....do whatever you want with the variable...accessing the

             .....contents via ObjectName.fieldName

    }

    Example (continuing example above):

    for(f in myCar) {

             document.writeln("You Car's " + f + " has the value: " + myCar.f);

    }

 

 

 

Part II: Understanding objects, methods and funtions

1. In this example, you'll use an object to perform a redundant task of laying out text in a HTML page.

Before you can use the Card object in this JavaScript example, you'll need to create a function to create any new Card objects. This definition is called the constructor.

function Card(name,address,work,home) {
     this.name = name;
     this.address = address;
     this.work_phone = work;
     this.home_phone = home;
}

The this refers to the current object, the one that is being created by the function.

 

2. You can also create methods to work with an object. They are defined as funtions and assigned in the object's contructor, so you don't need ask for any parameters. First, you'll need to define it:

function PrintCard() {
     document.write("<B>Name:</B> ", this.name, "<BR>");
     document.write("<B>Address:</B> ", this.address, "<BR>");
     document.write("<B>Work Phone:</B> ", this.work_phone, "<BR>");
     document.write("<B>Home Phone:</B> ", this.home_phone, "<HR>");
}

This method uses a built-in object of JavaScript, the document object, and one of its properties, write. It will allow the script to print out the results of this method.

 

3. Now place an additional line in the constructor (in red), so that the method is part of the Card object

function Card(name,address,work,home) {
     this.name = name;
     this.address = address;
     this.work_phone = work;
     this.home_phone = home;
     this.PrintCard = PrintCard;
}

 

4. Since the Card object is defined to accept a name, address,work and home variable, now you can create a new Card object like this

tom = new Card("Tom Jones", "123 Elm Street", "555-1234", "555-9876");

This is called a function call. By calling the function, or the object definition, you can create a new object. Once the statement executes, the new tom object is refered to as an instance of the Card object.

 

5. And once you create an instance of the Card object, you can use the PrintCard() method to print out the information:

tom.PrintCard();

 

6. Now put it all together Notice how the method and constructor are defined while still inside the <HEAD> tag and the instances are executed inside the <BODY> . The lines beginning with // are remark lines and are ignored by the browser within the <SCRIPT> tags:

<HTML>
<HEAD>
<TITLE>JavaScript Business Cards</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function PrintCard() {
   document.write("<B>Name:</B> ", this.name, "<BR>");
   document.write("<B>Address:</B> ", this.address, "<BR>");
   document.write("<B>Work Phone:</B> ", this.work_phone, "<BR>");
   document.write("<B>Home Phone:</B> ", this.home_phone, "<HR>");
}
function Card(name,address,work,home) {
   this.name = name;
   this.address = address;
   this.work_phone = work;
   this.home_phone = home;
   this.PrintCard = PrintCard;
}
</SCRIPT>
</HEAD><BODY>
<H1>JavaScript Business Card Test</H1>
Script begins here.<HR>
<SCRIPT LANGUAGE="JavaScript">
// Create the instances of the Card object
sue = new Card("Sue Suthers", "123 Elm Street", "555-1234", "555-9876");
phred = new Card("Phred Madsen", "233 Oak Lane", "555-2222", "555-4444");
henry = new Card("Henry Tillman", "233 Walnut Circle", "555-1299", "555-1344");
// And print them
sue.PrintCard();
phred.PrintCard();
henry.PrintCard();

</SCRIPT>
End of script.
</BODY>
</HTML>

 

Next: Understanding Event Handlers and the window Object