User:Jesdisciple/JavaScript/Functions and Objects

Functions
Functions allow you to split your code up into separate parts. This commonly allows a complex task to be broken up into several simple tasks, which then become easier to manage and control. When you put your script into a function it keeps the browser from executing the script when the page loads. It contains a code that will be executed by an event or call to that function. It can be called from anywhere within a page or even in an external page. While they can be defined in both and sections it is commonly used in and highly recommended to be used in the portion in order to have your function load before the rest of the page.

Functions are defined with. To call a function, use.

Functions without arguments
Let us create a function that will perform for us the one of the most common examples when beginning programming. That of saying "Hello, World!"

The above code is saying:
 * create a function called helloWorld
 * that doesn't expect any arguments
 * and perform the following statement, to alert a message

When we want to invoke this function in our HTML document, we call the function in the following manner:

Let's put this together on a sample web page.

Example
Since the line "alert("Hello World!")" was placed in a function it will not display until the button is clicked, in which case the alert will pop up.

Functions with arguments
Let's start with a quick example, then we will break it down.

This program takes a number as an argument. If the number is larger than 5, it subtracts one. If it's smaller than five it adds one. Let's get down and dirty and look at this piece by piece.

This is similar to what we've seen before. We now have  following the function name. This is where we define our arguments for later use, which is similar to defining variables, except in this case the variables are only valid inside of the function.

If statements. If the condition is true, execute the code inside the curly brackets.

Assuming that JavaScript is your first language, you might not know what this means. This takes one off from the variable. You can think of it as a useful shorthand for.

This is similar to the last one, except that it adds one instead of subtracting it.

This returns the value of number from the function. This will be covered in more depth later on.

Here is an example of using this in a page.

There are a few more things to cover here.

This is where the return statement in the function comes in handy. here gets assigned the number 5, since that is what stepToFive will return when it's given an argument of 6.

Objects
The philosophy of object-oriented programming says that program code should be as modular as possible. Once you've written and tested a function, it should be possible to slot it into any program or script needing that kind of functionality and just expect it to work, because it's already been tried and tested on an earlier project.

The benefits of this approach are a shorter development time and easier debugging, because you're re-using program code that has already been proven. This 'black box' approach means that data goes into the Object and other data comes out of the Object, but what goes on inside it isn't something you need to concern yourself with.

An Object is a code structure that has its own private variables, and stores data that is isolated from outside interference. Only the Object itself can alter this data. The user works with the data through a set of public functions (called Methods) for accessing these private variables. It's probably most convenient to consider that an Object has its own set of functions that allows you to work with it in certain ways.

While JavaScript allows creating of objects, you will discover that access protection are not directly available in JavaScript; as such, it is possible to bypass the intent of the object-oriented programming by directly accessing fields or methods. To minimize the impact of these issues, you may want to ensure that methods are properly described and cover known situations of use - and to avoid directly accessing methods or fields that are designed to hold the internal state of the object.

Javascript provides a set of predefined Objects. For example: the document itself is an Object, with internal variables like 'title' and 'URL'.

The Date Object
Let's look at the  Object. You can create a new object and assign it to a variable name using the new keyword:

The Date Object has a set of internal variables which hold the time, day, month, and year. It allows you to refer to it like a string, so you could for example pop-up the time that the variable was created. A pair of lines like this:

would display an alert box showing the current time and date, in universal time, like this:

Even though it produced a string, the variable myDate is not actually one itself. An operator called typeof returns a string that indicates what type the variable is. These types are:
 * boolean
 * function
 * number
 * object
 * string
 * undefined

So the following code:

would produce:

The Date Object stores a lot of information about the date, which are accessed using a certain predefined method. Some examples of these methods are:
 * getFullYear
 * getMonth
 * getDate
 * getDay
 * getHours
 * getMinutes
 * getSeconds

The following code shows the year and what type of object that information is.

Because information such as the year are private to the object, the only way we have to alter that information is to use a method provided by the Object for that purpose.

The above methods to get information from the Date object have matching methods that allow you to set them too.
 * setFullYear
 * setMonth
 * setDate
 * setDay
 * setHours
 * setMinutes
 * setSeconds

The following code will show one year, followed by a different year.

Defining New Classes
Example:

What this example does is:
 * Define site as an empty object
 * Add a method called test to the site object
 * Call the test method with variable "Boo!"

The result is:
 * An alert message with "Hello World! Boo!"
 * site.string being defined as string
 * An alert message with "Boo!".

In summary
An object is a structure of variables and some functions used to work with those variables. These include private variables, which can (or in JavaScript's case, should) only be referenced or changed using the methods it provides. If a  object's   method returns an incorrect value, you can depend on the fact that somewhere in your script, the   method has been used to alter it.

this keyword
The  keyword allows a method to read and write the property variables of that instance of the object.

The following example uses an initial capital letter for  to help indicate that the object needs to be created with the   keyword.

Exceptions
In Javascript, errors are created by the Error object and its subclasses. To catch the error to prevent it from stopping your script, you need to enclose sections of your code with the try...catch block.

Errors have two important fields: Error.name - which is the name of the error, and Error.message - a human readable description of the error.

While you can throw any object you want as an exception, it's strongly recommended to throw an instance of the Error object.