Objects in JavaScript are "EveryThing", cause almost "Everything" in JavaScript is an Object. in fact, if you understand Objects, You understand JavaScript.
An object in JavaScript is a variable that contains variables. An object has properties and methods.
if a car is our object per example, the car here has properties and methods, properties like; its color, name, model, weight, and methods like; stop, brake, start, ... etc
To create an Object in JavaScript, you have THREE different ways to do so :
- Using an object Literal.
- Using the new keyword.
- Using an object construction.
This way, you define and create the object at the same time, and it's the easiest way to create an object.
to create an object literal, we use, let, then the name of our object, the equal sign "=", the curly brackets { }, and then inside, the name:value pairs separated by commas ","
Example :
let car = { name : "Mercedes", model :2018, color : "Black" };
Using the new keyword.
to create the same object above, using the new keyword, we first create the object, like this:
let car = new Object();
and then we define the object car properties and methods, like this :
PS: for fast execution, use the object literal way.
This is useful when you want to create many objects under the same category, what I mean, say you have a list of cars, Audi, Mercedes, Volkswagen, Renault, ... etc
And they all have the same properties and methods, (name, color, model, start, brake ... ).
And then You use the object literal way, you will do something like this :
let mercedes = { name : "Mercedes", model :2018, color : "Black" };
let audi = { name : "Audi", model :2017, color : "Yellow" };
let renault = { name : "Renault", model :2016, color : "White" };
It sounds like your wasting time, and type in the same code over and over.
The solution here is using a construction function. You create a function and reuse the code whenever you want. Read Functions in JavaScript.
let's create our construction function:
function Car(){ }
The first letter of our construction function in upper-case. ( good practice )
and then inside the curly brackets {}, we create the properties and the methods.
function Car(name, model, color){
this.name = name;
this.model = model;
this.color = color;
}
now it's so easy to create as many instances of the object car as we want, and it's done by simply doing this :
let mercedes = new Car("Mercedes", "2018", "Black");
let audi = new Car("Audi", "2017", "Yellow");
let renault = new Car("Renault", "2016", "White");
if you want to see this article in action, you can watch my tutorial about JavaScript Objects below.
Tags:
JavaScript
I think you should use const instead of let when dealing with objects as the variable is pointing to their reference and not their values.
ReplyDeleteYes You're right.
DeleteThanks for your comment !