Objects in javascript:
Object in
javascripts is an entity having properties and methods. For example: car pen
etc.
Javascript is
object oriented language. Javascript is
not class based language it is template based. So without class we can create
object in javascript directly.
How to create objects in javascript:
There are
three methods to create objects:
1. By object
literal
2. By creating
instance of Object directly (using new keyword)
3. By using an
object constructor (using new keyword)
1. Javascript object by Object Literal:
Syntax of
creating object using object literal:
Obj_name={property1:value1,
property2:value2,property3:value3,…..}
Example:
<script>
student = { name: "ankit", age: 22, class: 10 }
document.write(student.name+" "+student.age+"
"+ student.class)
</script>
2. By creating Instance of object:
Syntax of creating
object directly:
var obj_name=
new Object();
We use new
keyword to create object.
Example:
<script>
var
student = new object();
student.name= "ankit";
student.age= 22;
student.class= 10;
document.write(student.name+" "+student.age+"
"+ student.class)
</script>
3. Using Object Constructor:
We create a function
with arguments. Each argument value can be assigned in current object by using “this
operator”.
“this operator” refers
to current object.
Example:
<script>
function
students(name, age, classs){
this.name=name;
this.age=age;
this.class=classs;
}
student=new
students("Ankit", 22,10)
document.write(student.name+" "+student.age+"
"+ student.class)
</script>
0 comments:
Post a Comment