JavaScript/Objects

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: Object-based programming Index Next: Constructors and prototypes

Objects[edit | edit source]

An object is a code container consisting of variables (properties) and functions (methods) which can be used to access and manipulate those properties and/or to provide additional functionality. Some properties are implemented as private variables, which should only be referenced or changed using the object's methods . Private properties and methods help ensure the integrity of object by only allowing changes under the object's control. For example, if a Date object's getFullYear() method returns an incorrect value, you can depend on the fact that somewhere in your script, the setFullYear() method has been used to alter it.

JavaScript provides a set of predefined objects. For example: an HTML document is itself (represented as) an Object, with internal variables like 'title' and 'URL' and methods like 'getElementsByClassName()'.

Basic example
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 the site variable as an object
  • define the site variable as a blank or empty object
  • define the site.test function
  • call the site.test function with variable "Boo!"

The result:

  • An alert message with 'Hello World! Boo!' will appear.
  • site.string will be defined as string
  • An alert message with 'Boo!' will appear.

The Date object[edit | edit source]

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

var mydate = new Date();

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:

var myDate = new Date();
alert(myDate);

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

Tue Jul 26 13:27:33 UTC+1200 2007

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:

var myDate = new Date();
alert(typeof myDate);

would produce:

object

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.

var myDate = new Date();
var year = myDate.getFullYear();
alert(year + '\n' + typeof(year));

2021
number

Because information such as the year is 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 the object's properties as needed. Since these properties can be changed only by using these methods, these methods typically contain code to ensure that the requested changes are proper changes to the Date object.

These methods are:

  • setFullYear()
  • setMonth()
  • setDate()
  • setDay()
  • setHours()
  • setMinutes()
  • setSeconds()

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

var myDate = new Date();
alert(myDate.getFullYear());
myDate.setFullYear(2008);
alert(myDate.getFullYear());
2021
2008

Defining new objects[edit | edit source]

var site = {};
site.test = function (string) {
    alert("Hello World! " + string);
    site.string = string;
}
site.test("Boo!");
alert(site.string);

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!".

Exceptions[edit | edit source]

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.

The new operator[edit | edit source]

The new operator creates a new instance of an object.

item = new Object();

Object methods and fields[edit | edit source]

In JavaScript, objects are free form - they can be modified at run time to instantly create a new object or to create new fields or functions.

money = new Object();
money.quarters = 10;

Object literals[edit | edit source]

Objects can also be created using the object literal notation.

money = {
    'quarters': 10
};

Further reading[edit | edit source]


Previous: Object-based programming Index Next: Constructors and prototypes