Classes and Objects in JavaScript

In Java, we can define our custom classes (constructors, fields and methods). In same way, we can also define the classes in JavaScript as well. Main difference between Java classes and JavaScript classes is that we can change the prototype of the class at run time.

Creating objects in JavaScript

var audiCar = {
        name: ‘Audi A8’,
       price:40000,
      color:’red’,
     getPrice: function () {
     return this.price;
},
setPrice: function (price) {
     this.price = price;
},
};
console.log(“Name of audiCar object -> ” + audiCar.name)
console.log(“Price of audiCar object -> ” + audiCar.getPrice())
audiCar.setPrice(50000)
console.log(“New Price of audiCar object -> ” + audiCar.getPrice())
console.log(“Color of audiCar object -> ” + audiCar.color)
console.log(“All keys of audiCar object -> ” + Object.keys(audiCar))
delete audiCar.color
console.log(“After deleting the Color of audiCar object -> ” + audiCar.color)
console.log(“All keys of audiCar object -> ” + Object.keys(audiCar))

Accessing properties of an object

You can access the properties of the object in 2 ways.

  1. object.propertyName
  2. object[“propertyName”]

For example – here we are calling bold method in 2 ways. Note that in second line, method name is inside double quotes.

“xx”.bold()
“xx”[“bold”]()

Creating properties using defineProperty

var jeepObject = {};
Object.defineProperty(jeepObject, ‘color’, {
value: ‘blue’,
configurable: true
});
Object.defineProperty(jeepObject, ‘price’, {
value: 60000,
configurable: false
});
console.log(“Color of the jeep object -> ” + jeepObject.color)

//Below statement will not show keys of the object as we have used defineProperty to create the keys

console.log(“All keys of jeep object -> ” + Object.keys(jeepObject))

console.log(“Color of the jeep object using [] -> ” + jeepObject[‘color’])

We can define the functions in 3 ways.

  1. Plain Functions – We have already seen plain functions earlier.
  2. Constructor – We can instantiate the objects using constructor functions.
  3. Method of a Object – When the property of the object is defined as a function, it is called as a method.

Creating classes in JavaScript

So far we have created individual objects. But in real world, we need to create multiple objects of the same class. We also need to create constructors to instantiate the objects.

function Car(name, manufacturer,price) {
this.name= name
this.manufacturer= manufacturer

this.price = price
this.getGrossPrice = function(){return this.price*1.2}
}

Now to create objects from the prototype, use below syntax

var car1 = new Car(“i30”, “Huyndai”, 340000);
var car2 = new Car(“A8”, “Audi”, 999999);
console.log(“car1 -> ” + car1.name)
console.log(“car2 -> ” + car2.name)

object-prototypes-in-javascript

object-prototypes-in-javascript

You may also like...