JavaScript Objects Part 4: Constructors and this
Tags: javascript, webdev, beginners
Published: 2021-03-30 07:38:21

### 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.   

```javascript
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
```
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.
```javascript
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}`);
    }
};
```

Lets create two objects *myCar* and *friendsCar* using the constructor *Car*
```javascript
let myCar = new Car("Hyundai", "i10", 2019, "petrol");      
let friendsCar = new Car("Hyundai", "i20", 2021, "diesel");
```

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.
```javascript
console.log(myCar.company);     //Output: Hyundai
console.log(myCar.year);        //Output: 2019
console.log(friendsCar.model);  //Output: i20
console.log(friendsCar.fuel);   //Output: diesel
```

Let's call the methods of the objects. 
```javascript
myCar.printDet();       //Output: Hyundai - i10 - 2019 - petrol
friendsCar.printDet();  //Output: Hyundai - i20 - 2021 - diesel
```

Now let's see what happen when we try to access a property that is not set.
```javascript
let newCar = Car("Audi", "A6", "2000");
console.log(newCar.fuel); // *undefined*
```
[Part 1: Object Basics](https://dev.to/kiranrajvjd/javascript-objects-part-1-4233) 
[Part 2: Dot vs Bracket](https://dev.to/kiranrajvjd/javascript-objects-part-2-dot-vs-bracket-3b3h)
[Part 3: In operator and for in statement](https://dev.to/kiranrajvjd/javascript-objects-part-3-in-operator-and-for-in-statement-e8d)
[Part 5: Object duplication ](https://dev.to/kiranrajvjd/javascript-objects-part-5-object-duplication-3dlg)