A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.
The this keyword refers to the current object.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<script>
var a = {
fname : 'Yahoo',
lname : 'Baba',
age : 25,
email: 'hello@yahoobaba.net',
}
console.log(a);
document.write(a.fname + "<br>");
document.write(a.email);
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<script>
var a = {
fname : 'Yahoo',
lname : 'Baba',
age : 25,
email: 'hello@yahoobaba.net',
favMovies: ['Dhoom', 'Sholay', 'Hum']
}
console.log(a);
document.write(a.favMovies[0]);
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<script>
var a = {
fname : 'Yahoo',
lname : 'Baba',
age : 25,
email: 'hello@yahoobaba.net',
favMovies: ['Dhoom', 'Sholay', 'Hum'],
salary : function(){
return 25000;
},
fullname : function(){
return this.fname + " " + this.lname;
}
}
document.write(a.salary() + "<br>");
document.write(a.fullname() + "<br>");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<script>
var a = {
fname : 'Yahoo',
lname : 'Baba',
age : 25,
email: 'hello@yahoobaba.net',
favMovies: ['Dhoom', 'Sholay', 'Hum'],
living : {
'city' : 'Chandigarh',
'country' : 'India'
},
salary : function(){
return 25000;
},
fullname : function(){
return this.fname + " " + this.lname;
}
}
document.write(a.fname + "<br>");
document.write(a.lname + "<br>");
document.write(a.age + "<br>");
document.write(a.email + "<br>");
document.write(a.favMovies + "<br>");
document.write(a.favMovies[0] + "<br>");
document.write(a.favMovies[1] + "<br>");
document.write(a.favMovies[2] + "<br>");
document.write(a.living.city + "<br>");
document.write(a.salary() + "<br>");
document.write(a.fullname() + "<br>");
</script>
</head>
<body>
</body>
</html>