JavaScript Object With Example
Objects in JavaScript
JavaScript is an Object Oriented Programming (OOP) language. A programming language is called object-oriented if it has the following four basic capabilities: encapsulation, aggregation, inheritance and polymorphism. All The objects will have properties and methods.
Object Properties
Syntax for adding a property to an object
objectName.objectProperty = propertyValue;
Example:
var str = document.title;
Object Methods
Example:
document.write("This is a method of the object document");
User-Defined Objects
Apart from built-in objects, the users can also create their own objects. All user-defined objects and built-in objects are descendants of an object called Object. The new operator is used to create a new object.
The new Operator
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
Example:
var books = new Array("Sweta","Kavya");
in the above example Array() is a built-in object. Books is the instance of the objectArray().
The Object() Constructor
A constructor is a function that creates and initializes an object. The Object() constructor is used to build an object. The return value of the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not variables. These properties can be accessed only through objects.
Syntax to access the properties:
Objectname.property
Example: Creating an object
Result:
Book name is : Coding for world Book author is : aimtocode
Defining methods for an Object
Methods can be created using the objects.
Example: Adding a function along with an object
Result:
Book title is : Coding for world Book author is : Pvpn Book price is : 400
In the above example, two methods are used. Book() is a constructor. So it does not need any object to access it.
addPrice() is a user defined method. It has to be accessed through an object.
Read In Details:
- JavaScript number Object
- JavaScript Native Object
- JavaScript Boolean Object
- JavaScript String Object
- JavaScript Array Object
- JaaScript Date Object
- JavaScript Math Object
- JavaScript RegExp Object