JavaScript – Objects

In JavaScript Objects are just data, with Properties and Methods.

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
 
<head>
<title>Title</title>
  
<script language="javascript">
// Object Creation START
var person=new Object();    // The object   is - person -
person.firstname="Andrea"// The property is - firstname -
person.lastname="Tonin";    // The property is - lastname -
person.age=39;              // The property is - age -
person.eyecolor="green";    // The property is - eyecolor -
// Object Creation END
 
// Accessing Object Properties - objectName.propertyName -
document.write(person.firstname + " is " + person.age + " years old." + "</br>");
// The result is "Andrea is 39 years old."
 
// Accessing Object Methods    - objectName.propertyName.methodName() -
document.write(person.firstname.toUpperCase());
// The result is "ANDREA"
 
</script>
 
<noscript>
Your browser does not support JavaScript!
</noscript>
  
</head>
   
<body>
... this is the web page content ...
</body>
 
</html>

The object is – person -, it is a sort of container.
The property is – firstname – with the value of “Andrea”
To access object Properties you can write – objectName.propertyName –
To access object Methods you can write – objectName.propertyName.methodName() –

Objects can be:
– Booleans
– Numbers
– Strings
– Dates
– Maths and Regular Expressions
– Arrays
– Functions

Using an Object Constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<body>
 
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
 
myFather=new person("Bruce","Lee",50,"brown");
myMother=new person("Brigitte","Bardot",48,"blue");
 
document.write(myFather.firstname + " is " + myFather.age + " years old.");
document.write(myMother.firstname + " is " + myMother.age + " years old.");
</script>
 
</body>
</html>

Adding Methods to JavaScript Objects:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
 
<head>
<title>Title</title>
  
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
  
this.changeName=changeName;
 
    function changeName(name)
    {
    this.lastname=name;
    }
}
myMother=new person("Brigitte","Bardot",48,"green");
myMother.changeName("Marilyn");
 
document.write(myMother.lastname); // The result is Marilyn
</script>
 
<noscript>
Your browser does not support JavaScript!
</noscript>
  
</head>
   
<body>
 
</body>
 
</html>

My official WebSite >