Everything is an Object
• In JavaScript almost everything is an object. Even primitype datatypes (exept null and undefined) can be treated as objects.
• Booleans can be objects or primitive data treated as objects
• Numbers can be objects or primitive data treated as objects
• Strings are also objects or primitive data treated as objects
• Dates are always objects
• Maths and Regular Expressions are always objects
• Arrays are always objects
• Even functions are always objects
JavaScript Objects
An object is just a special kind of data, with properties and methods.
• Accessing Object Properties
Properties are the values associated with an object.
The syntax for accessing the property of an object is: objectName.propertyName This example uses the length property of the String object to find the length of a string: var message="Hello World!"; var x=message.length;
Accessing Objects Methods
Methods are the actions that can be performed on objects.
You can call a method with the following syntax: objectName.methodName() This example uses the toUpperCase() method of the String object, to convert a text to uppercase: var message="Hello world!"; var x=message.toUpperCase();
Creating JavaScript Objects
• With JavaScript you can define and create your own objects.
There are 2 different ways to create a new object:
– 1. Define and create a direct instance of an object.
– 2. Use a function to define an object, then create new object instances.
Creating a Direct Instance
person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";
Alternative syntax (using object literals):
Example
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Using an Object Constructor
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }
Once you have a