Tuesday, 3 April 2018

Object In JavaScript

A JavaScript object is an entity having state and behavior (properties and method). Example:mouse, car, pen, bike, chair, apple, keyboard, monitor etc.
Objects are variables too. But objects can contain many values.

Imp points:
The values are written as name:value pairs(name and value is separated by  a colon). The name:values pairs in JavaScript objects are called properties. 
var emp = {Name:"surya", address:"pune", age:20, salary:35000.56};


Property
Property Value
Name
surya
address
pune
age
20
salary
35000.56

JavaScript is template based not class based. So we don't create class to get the object. But, we direct create objects.


Creating Objects in JavaScript
There are 3 ways to create objects.
1.     By object literal
2.     By creating instance of Object directly (using new keyword)
3.     By using an object constructor

1) JavaScript Object by object literal
Syntax:
object={property1:value1,property2:value2.....propertyN:valueN}  

     Example:

<script> 

emp={name:"surya", address:"pune", age:20, salary:35000.56};

document.write(emp.name+" "+emp.address+" "+emp.age+" "+emp.salary); 

</script> 

Output :

surya pune 20 35000.56

2) By creating instance of Object

Syntax:
var objectname=new Object();  
where new is a  keyword which is used to create object.

Example:

<script> 

var emp=new Object(); 

emp.name="surya"; 

emp.address="pune"

emp.age=25;

emp.salary=35000.56; 

document.write(emp.name+" "+emp.address+" "+emp.age+" "+emp.salary);  

</script>

Output :

surya  pune  20  35000.56

3) By using an Object constructor
this keyword refers to the current object.
So you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.

Example:
  <script>  
   function stu(age,name,mark){  
   this.age=age;  
   this.name=name;  
   this.mark=mark;  
    } 
   ob1=   new stu (10,"surya",50);
   document.write(ob1.age+" "+ ob1.name+" "+ ob1.mark);  
  </script>  
   Output :
10 surya 50

1 comment:

  1. Python is an open-source, high level, interpreted programming language which offers great opportunities for object-oriented programming. Choosing a python training program from Red Prism Group, which is best training institute for python in noida.

    ReplyDelete

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...