JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.
The syntax for accessing the property of an object is:
objectName.propertyName
example:
var message="Hello World!";
var x=message.length;
The value of x, after execution of the code above will be:
12
Note how message is the object.
Here's another example where you instantiate the object using new, and add properties to it.
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
Now, here's a class example:
function HelloWorld(hour)
{
// class "constructor" initializes this.hour field
if (hour)
{
// if the hour parameter has a value, store it as a class field
this.hour = hour;
}
else
{
// if the hour parameter doesn't exist, save the current hour
var date = new Date();
this.hour = date.getHours();
}
// display greeting
this.DisplayGreeting = function()
{
if (this.hour >= 22 || this.hour <= 5)
document.write("Goodnight, world!");
else
document.write("Hello, world!");
}
}
In this example, HelloWorld is the class.
key : valuepair only.You cannot put an statement there.