Methods and Functions


Methods are behaviors applied on objects. Different objects have different methods available. Additional methods may be created, by writing appropriate JavaScript functions.

Besides their traditional use, functions in JavaScript can be used not just as object methods, but also as constructors and event handlers.

Method and function invocation

  • Methods are also specified using the dot notation, with the object name(s) on the left and the method or function name on the right, with parameters enclosed in parentheses.

  • Parentheses are always required even when no parameters are used
    • object-name.method-name(parameters)
    • object-name.function-name(parameters)
    • document.write("Hello there") // -- write method

    • var sometext = "Hi Ed";
      UpperCasedText = sometext.toUpper()

  • When used as an event handler, a function is called in a traditional assignment invocation; examples:

    • <BODY onload="checkBrowser()">

    • <A HREF="somewhere.junk.html onclick="confirm('Are you sure?')">Click here to visit some junk site</A>

    • <A HREF="javascript:justDoit(foo,env,mon)">Apply changes</A>

Defining a function in JavaScript

This is similar as in most other programming languages, namely:

function function-name(parameter-list) {
...
body of the function
...
}

where parameter-list is the list of parameters, separated by commas. The values are assigned to the function local variables named (within parentheses), passed by name.

Data type and number of of arguments are not checked in JavaScript. A return statement is also optional.

Sample function that loads the appropriate browser-specific HTML

 

JavaScript Seminar Home | Previous | Next


Last Modified: March 2, 2001— UIC Instructional Technology Lab