Table of Contents
JavaScript Objects
A JavaScript object is a variable which stores multiple data in the form of key and value pairs separated by a colon.
This key (or name) value pair together is called property of an object.
Example: An object with Employee Data
var person = {firstName: “Priyanka”, lastName: “Pandey”, age: 22, education:”MCA”};
Creating an Object
We can create an object using given three ways:
- Using Object Initializers
In this method of object creation, we directly create a variable and define it like an object with key and value pair.var obj = {key1: “value1”, key2: “value2”, …..., keyN: “valueN”}; var person = {firstName: “Hitesh”, lastName: “Goel”, age: 23}
or, simply by defining a variable and assigning it an empty object as shown below:
var obj = {};
- Using a constructor function
In this method of object creation, we follow given two steps:- We define the object type by writing a constructor function.
- Create an instance of the object with new.
Example: An object person with its properties
Constructor Function
function employee(firstName, lastName, dob) { this.firstName = firstName; this.lastName = lastName; this.dob = dob; }
Instance of the Constructor
var person = new employee('Aditya', 'Farrad', 1994);
In the above example, we have created a JavaScript function and named it employee. Then for every new object creation, we will call this function with the values. Here the keys are fixed as firstName, lastName and dob. this in the function is a JavaScript keyword which refers to the current object.
- Using the create method
This method creates a new object using an existing object as a prototype.
var newPerson = Object.create(person);
Here, we have created a new object newPerson using the object person created in the method 1 above as a prototype.
Access an element of an Object
We can access an element [in case of object, property] of an object in given two ways:
- propertyName
Example: person.firstName;
- objectName[“propertyName”]
Example: person[“firstName”];
0 Comments