A class is a set or category of things having some property or attribute in common i.e., car is a class having similar properties such as color, engine, gear, model number etc.
The “class” construct allows us to define prototype-based classes.
Syntax for declaring a class:
1 2 3 4 5 6 7 8 9 10 | class User { constructor(name) { this.name = name; } display() { alert(this.name); } } let user = new User("Sherlock"); user.display(); |
Objects
Objects are the instance of classes i.e., Car is a class and Jaguar is an object of the Car class
Let’s consider a variable named person:
var person = “Sherlock Holms”;Objects are also like variables but they can contain many values; like
this code assigns many values (Sherlock, Holms, male) to a variable named person:
var person = {name:”Sherlock”, title:”Holms”, gender:”male”};The values are written as name:value pairs.
Object Definition
var person = {FirstName:”Sherlock”, lastName:”Holms”, age:50};
Spaces and line breaks are not important. An object definition can span multiple lines:
1 2 3 4 5 | var person = { firstName: "Sherlock", lastName: "Holms", age: 50 }; |
Object Properties
The name:values pairs in JavaScript objects are called properties:
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 30 |
Accessing Object Properties
Object properties can be accessed in 2 ways:
- objectName.propertyName
or
2. objectName[“propertyName”]
Access Method 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <body> <h3>JavaScript Object Access Method 1</h3> <p id="demo"></p> <script> var person = { firstName: "Sherlock ", lastName: "Holms", id: 5266 }; document.getElementById("demo").innerHTML = person.firstName + "" + person.lastName; </script> </body> </html> |
Output
1 2 | JavaScript Object Access Method 1 Sherlock Holms |
Access Method 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html> <body> <h3>JavaScript Objects</h3> <p> JavaScript Object Access Method 2 </p> <p id="demo"></p> <script> var person = { firstName: "Sherlock", lastName: "Holms", id: 5266 }; document.getElementById("demo").innerHTML = person["firstName"] + "" + person["lastName"]; </script> </body> </html> |
1 2 | JavaScript Object Access Method 2 Sherlock Holms |