Wednesday, February 19, 2020

Object In JavaScript

Object In JavaScript

Object


An Object is a set of properties, and a property can be defined as a key-value pair. The value can be another object, a simple or complex type, or a function. The Objects are like variables but they can hold multiple values as arrays do. The Objects are different from arrays because the values in arrays are indexed by numbers but in Objects, the values are identified by keys.

Creating the Objects


An object can be created as,


employee_obj={
            eid:117,
            ename:"Harry",
            edept:"CSE"
            };

OR


var car=new Object();
car.mfdby='Toyota';
car.model='Camry'
car.mfdyear='2015'


Accessing the Objects


The objects are very much like real-life tangible objects. We can uniquely identify and compare them because they are standalone and independent entities. The value of the property can be accessed by the (.) dot operator on the object name followed by the property name.


objectName.propertyName


OR

objectName[propertyName]


The value of objectName.propertyName will be undefined until it is set to some value. JavaScript object property names (keys) can only be strings or Symbols. We should not create simple type(boolean, number, or string) objects using the new keyword as it will add complexity to our code.

Using a method as a property(object methods)


We can also provide a method as a property value. These actually object methods.

<script>
  rectangle={
            ht:25,
            wd:30,
            cal_area:function(){
                     return 'Area of rectangle is '+this.ht*this.wd;
                               }
             };
    document.write(rectangle.cal_area());
</script>

Output:
Area of rectangle is 750

The "this" Keyword 


The keyword "this" refers to the "owner" of the method. In the example above, this is the "rectangle" object that "owns" the cal_area() method. "this" is an implicit reference for the object members created by the runtime itself.



Example,