Objects in JavaScript
JavaScript is an Object Oriented Programming language (Object Oriented Programming). A Program Language can be called object-oriented if it provides four basic capabilities to the programmer:
- Encapsulation - The ability to store related information, data or methods, together in an object.
- Aggregation - The ability to store an object inside another object.
- Inheritance - The ability of a class to rely on another class (or several classes) for some of its properties and methods.
- Polymorphism - The ability to write a function or method that works in a variety of different ways.
Objects include attributes. If an attribute contains a function, it is said to be a method of the object, otherwise the attribute is considered an attribute.
Properties of the object
Object properties can be any of the three primitive data types, or in abstract data types (abstract), such as other objects. Object properties are often variables that are used within object methods, but can also be visible global variables that are used throughout the site.
The syntax for adding an attribute to an object is:
objectName . objectProperty = propertyValue ;
For example - The following code receives the document title by using the " title " attribute of the Document object:
var str = document . title ;
Object method
Methods are functions that instruct the object to do something or instruct something to be done to it. There is a small difference between a function and a method: a function is an independent unit of commands and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the content of on-screen objects to performing complex operations on a group of internal properties and parameters.
Example - The following is a simple example to show how to use the write () method of document object to write any content on the document.
document . write ( "This is test" );
User defined objects
All user objects define themselves (User-defined Objects) and the available object is a child of an object called Object .
New operator
The new operator is used to create an object. To create an object, the new operator is followed by the constructor method.
In the following example, constructor methods are Object (), Array (), and Date (). These constructors are built-in functions in JavaScript.
var employee = new Object (); var books = new Array ( "C++" , "Perl" , "Java" ); var day = new Date ( "August 15, 1947" );
Object () Constructor
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object () to build an object. The return value of Object () constructor is assigned to a variable.
This variable contains a reference to the new object. Attributes assigned to the object are not variables and are not defined with the var keyword.
Example 1
Try the following example. It illustrates how to create an Object.
User-defined objects