JavaScript Objects
JavaScript
is an object based language.
Object
can be created in two ways
1.
Creating a direct instance
2.
Creating an object using a functional template
Creating a direct
instance
Direct instance of an object is created by using a new
keyword.
Obj = new object();
Properties and method are added to object using period (.)
Obj.name =”Adam”;
Obj.job =”Software engineer”;
Obj.getSalary();
Creating an object
using functional template
Instance of an object is created by creating a functional
template of an object. After creating the functional template, we need to
create the instance of the functional template by using the new keyword. A functional
template of an object is created by using function keyword. Properties can be
added to the function template by using the this keyword.
function employee(name,
designation, salary)
{
this. name =name;
this.designation =designation;
this.salary =salary;
}
Now, creating an instance of the
employee object
var team_employee= new
employee(“adam”,”S.E”,24000);
Accessing the team_employee
instance of the employee object.
var employee_designation=
team_employee.designation;
Properties/attributes of an object
Also known as the characteristics
of an object. Properties of an object can be added using the this keyword
followed by the period (.).
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Objects</title>
<script>
function employee(name, designation) {
this.name = name;
this.designation = designation;
this.salary = 24000;
}
var employee_object = new employee('Adam', 'S.E');
alert(employee_object.designation);
document.write(employee_object.salary);
</script>
</head>
<body>
<h1>JavaScript Objects</h1>
</body>
</html>
Methods of an object
Method is a collection of
statement that are executed when called by its name.
Adding a method to a user defined
object.
- . Declaring and defining a function for each method
- Associating a function with an object
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Objects</title>
<script>
function computearea() {
var area = this.base * this.altitude * 0.5;
return area;
}
function triangle(b, a) {
this.base = b;
this.altitude = a;
this.area = computearea;
}
var triangle_object = new triangle(10, 20);
alert("area= " + triangle_object.area());
</script>
</head>
<body>
<h1>JavaScript Objects</h1>
</body>
</html>
0 comments:
Post a Comment