Objects
An object is a non-primitive data type. It is a collection of related data or functionality. These consists of several variables and functions which are called properties and methods of the object.
Example:
var Student = {name: "Prajwal", age: "20"}; // Student object with two properties
Almost everything in javascript is an object. All javascript values such as Booleans, Strings, Numbers, Maths, Dates, Regular Expressions, Array and Functions are all objects.
Creating an Object
- Using an object literal:
var Car = {company: "Lamborghini", name: "Aventador", year: "2020"};
- Using new keyword:
var Car = new Object();
Car.company = "Lamborghini";
Car.name = "Aventador";
Car.year = "2020";
Adding New Properties to an Object
- Dot notation
Car.color = "royal blue"
- Bracket notation
Car['color'] = "royal blue"
Deleting Properties from an Object
delete Car.color;
Adding a Method to an Object
Car.fullname = function() {
return this.company + " " + this.name;
};
Built-In Constructors
- New Object object
var a = new Object();
- New String object
var a = new String();
- New Number object
var a = new Number();
- New Boolean object
var a = new Boolean();
- New Array object
var a = new Array();
- New Regular Expression object
var a = new RegExp();
- New Function object
var a = new Function();
- New Date object
var a = new Date();
Using this for Object References
The keyword this is used in javascript to refer to the properties of the current object.
var Car1 = {name: "Lamborghini"};
var Car2 = {name: "Ferrari"};
function display() {
console.log("Car name is: ", this.name);
}
Car1.display = display;
Car2.display = display;
Car1.display(); // Lamborghini
Car2.display(); // Ferrari
Objects play a very important role in javascript and I hope you've understood them well by now.
Thank You!
Top comments (0)