Syntax for adding a property to an object
objectName.objectProperty = propertyValue;
var str = document.title;
document.write("This is a method of the object document");
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.
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:
Example: Creating an object
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
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:
- JaaScript Date Object