JavaScript/Functions and Objects 2

From Wikibooks, open books for an open world
< JavaScript
Jump to: navigation, search

Functions[edit]

A Javascript function is a code-block that can be reused. It can be called via an event, or by manual calling.

Basic Example[edit]

function myFunction(string) {
	alert(string);
	document.innerHTML += string;
}
myFunction("hello");

The example would first:

  • Define the myFunction function
  • Call the myFunction function with arguement "hello"

The result:

  • An alert message with 'hello'
  • The string 'hello' being added to the end of the document's/page's HTML.

Objects[edit]

The great thing about Javascript is that it is an OOP (Object Oriented Programming) language. This means that with an OOP language, you can make your own objects (like the document object) and even define your own variable types.

Basic Example[edit]

var site = new Object(); //Required to not cause error in Internet Explorer
site = {};
site.test = function(string) {
	alert("Hello World! "+string);
	site.string = string;
}
site.test("Boo!");
alert(site.string);

The example would first:

  • Define site as an object
  • Define site as a blank object
  • Define site.test function
  • Call the site.test function with variable "Boo!"

The result:

  • An alert message with 'Hello World! Boo!'
  • site.string being defined as string
  • An alert message with 'Boo!'.