C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript ObjectsA javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard, monitor etc. JavaScript is an object-based language. Everything is an object in JavaScript. JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects. Creating Objects in JavaScriptThere are 3 ways to create objects.
1) JavaScript Object by object literalThe syntax of creating object using object literal is given below: object={property1:value1,property2:value2.....propertyN:valueN} As you can see, property and value is separated by : (colon). Let’s see the simple example of creating object in JavaScript. <script> emp={id:102,name:"Shyam Kumar",salary:40000} document.write(emp.id+" "+emp.name+" "+emp.salary); </script> Output of the above example2) By creating instance of ObjectThe syntax of creating object directly is given below: var objectname=new Object(); Here, new keyword is used to create object. Let’s see the example of creating object directly. <script> var emp=new Object(); emp.id=101; emp.name="Ravi Malik"; emp.salary=50000; document.write(emp.id+" "+emp.name+" "+emp.salary); </script> Output of the above example3) By using an Object constructorHere, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword. The this keyword refers to the current object. The example of creating object by object constructor is given below. <script> function emp(id,name,salary){ this.id=id; this.name=name; this.salary=salary; } e=new emp(103,"Vimal Jaiswal",30000); document.write(e.id+" "+e.name+" "+e.salary); </script> Output of the above exampleDefining method in JavaScript ObjectWe can define method in JavaScript object. But before defining method, we need to add property in the function with same name as method. The example of defining method in object is given below. <script> function emp(id,name,salary){ this.id=id; this.name=name; this.salary=salary; this.changeSalary=changeSalary; function changeSalary(otherSalary){ this.salary=otherSalary; } } e=new emp(103,"Sonoo Jaiswal",30000); document.write(e.id+" "+e.name+" "+e.salary); e.changeSalary(45000); document.write(" Output of the above exampleJavaScript Object MethodsThe various methods of Object are as follows:
Next TopicJavascript Array
|