DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for JavaScript Objects Part 4: Constructors and this
Kiran Raj R
Kiran Raj R

Posted on • Updated on

JavaScript Objects Part 4: Constructors and this

this

We know that the object properties can have functions as their value, we call those functions as methods. In some cases the methods may need to get property value of the same object. We can get the value by objectname.propertyKey but this is not considered as an efficient method. Consider when we change the name of the object, we need to rewrite every instance where we use the object name to access a property value. How can we access property more efficiently? That is when the this keywords comes, we can use this to get information stored in the object in which the method exists. Let's look at this with an example.

let admin1 = {
    fname: "kiran",
    lname: "raj",
    admin: true,
}

let admin2 = {
    fname: "Rajeesh",
    lname: "",
    admin: true
}

let admin3 = {
    fname: "Vishnu",
    lname:"R",
    admin: true,
}

function GreetAdmin(){
    console.log(`Hello ${this.fname} ${this.lname}`);
}

admin1.greet = GreetAdmin;
admin2.greet = GreetAdmin;
admin3.greet = GreetAdmin;

admin1.greet();             // Hello kiran raj
admin2.greet();             // Hello Rajeesh
admin3.greet();             // Hello Vishnu R
Enter fullscreen mode Exit fullscreen mode

We have three objects admin1, admin2, admin3, all have properties fname, lname with values. Then we add a method GreetAdmin to all objects with a key greet. The GreetAdmin only have a console statement which prints the value of this.fname and this.lname. If we simply call GreetAdmin() we get Hello undefined undefined, because we are calling the function in the global scope and this will be pointing towards the object that is calling it, here it is the global object (window in case of the browser) and the global object does not have any lname or fname variables so the output will be Hello undefined undefined. Let's call the greet method of object admin1, admin1.greet(), when we call admin1's greet method the this will be pointing to calling object, here it is admin1. The output of greet method will be Hello kiran raj(this.fname will get the fname's value of admin1 and this.lname will get the lname's value of admin1). Output will change according to the fname and lname values of objects that are calling the greet method.

When a function is declared, this has no value, it will not get a value until the function is called. When we call object.method(), this will be pointing towards the object. The arrow function does not have this.

Constructor

Constructor functions are basically regular function which starts with a capital letter. Constructor function is used to create multiple instance of an object. Constructor should be executed with new operator. Main purpose of constructor function is code reusability. A constructor consists of constructor name, properties and method. We use this to assign values to the properties that are passed to constructor function during the object creation.

An constructor example is given below.

function Car(company, model, year, fuel){
    this.company = company;
    this.model = model;
    this.year = year;
    this.fuel = fuel;
    this.printDet = function(){
        console.log(`${this.company} - ${this.model} -${this.year} 
                   - ${this.fuel}`);
    }
};
Enter fullscreen mode Exit fullscreen mode

Lets create two objects myCar and friendsCar using the constructor Car

let myCar = new Car("Hyundai", "i10", 2019, "petrol");      
let friendsCar = new Car("Hyundai", "i20", 2021, "diesel");
Enter fullscreen mode Exit fullscreen mode

The myCar and friendsCar objects are created using Car constructor. The Car construct sets properties company, model, year, fuel and a method prientDet to the newly created objects, myCar and friendsCar. The passed values, "Hyundai", "i20", 2021, "diesel" are set as the values of properties (company, model, year, fuel) in myCar object and "Hyundai", "i20", 2021, "diesel" values as property values in friendsCar object.

Lets look what happens when we use new operator.

  1. An new empty object is created, it is linked to [[Prototype]].
  2. this points to the new empty object.
  3. The properties and methods are added to the new object.
  4. The passed values are set to those properties.
  5. The value of the this is returned, unless we specify another return object.

Newly created object inherits the prototype of the constructor function.

Lets see the value of the properties of the newly created objects.

console.log(myCar.company);     //Output: Hyundai
console.log(myCar.year);        //Output: 2019
console.log(friendsCar.model);  //Output: i20
console.log(friendsCar.fuel);   //Output: diesel
Enter fullscreen mode Exit fullscreen mode

Let's call the methods of the objects.

myCar.printDet();       //Output: Hyundai - i10 - 2019 - petrol
friendsCar.printDet();  //Output: Hyundai - i20 - 2021 - diesel
Enter fullscreen mode Exit fullscreen mode

Now let's see what happen when we try to access a property that is not set.

let newCar = Car("Audi", "A6", "2000");
console.log(newCar.fuel); // *undefined*
Enter fullscreen mode Exit fullscreen mode

Part 1: Object Basics
Part 2: Dot vs Bracket
Part 3: In operator and for in statement
Part 5: Object duplication

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.