Ad Code

Responsive Advertisement

Objects

Introduction

  • Object in JavaScript is a type of variable.
  • Object represents a real world things[entities].
  • for eg. car is an object, a computer is a object, etc.
  • object stores key and value pair
  • objects can be created mainly in two ways: Literal way and constructor way.

Literal Way of Creating an Object

  •  eg. let customer={custName:"Harry", custAddress:"TKP"};
  • customer is an object name, custName is a key where Harry is the value of custName, similarly, custAddress is a key name and TKP is the value of that key custAddress.
  • we can simply define only. Later we can assign value to the object.
  •   e.g let customer={}; // It is called literal way of creating obj.
  • And then objName.keyName="<value>";
  • To access objects : objName.keyName;
    • eg. alert(customer.custName);
<script>
        let customer={custName:"Harry", custAddress:"TKP"};
        console.log("Name: "+ customer.custName +", Address: "+customer.custAddress);

        let car = {
            name:"Suzuki",
            model:"SZ123",
            color:"Black",
        };
        console.log(`Car Name : ${car.name}`); 

        // or we can create object in different way. First create a empty obj and
            then push the key-values.
        let person = {};
        person.name="Harry";
    </script>


Constructor ways of creating an object

- The another method of creating an object is using 'new' keyword with object().
- To create an object, first we need a constructor funtion.
- let's understand through an example:

<script>
        function account(){
            this.id="101";
            this.accHolder="Maxx";
            this.balance="10000";

            this.status = function status(){
                alert("Active");
            }
        }

        let x = new account();  // creating an instance of account. This is the 
// construction way of creating an object.
        x.status();
        console.log(x); // x is here an objec, 
//account {id: "101", accHolder: "Maxx", balance: "10000", status: Æ’}

        console.log("ID: "+ x.id);   
        console.log("Name: "this.accHolder);   // here accHolder is not in 
//lexical scope Name: undefined
    </script>

In the above code, account() is a constructor function we've
created that holds some variables and function status() is a
closure function.

we can create more objects like x. eg
let x1 = new account();
let x2 = new account();



Post a Comment

0 Comments