Interface

  • An interface is similar to a class except that it cannot contain code.
  • An interface can define method names and arguments, but not the contents of the methods.
  • Any classes implementing an interface must implement all methods defined by the interface.
  • A class can implement multiple interfaces.
  • An interface is declared using the “interface” keyword.
  • Interfaces can’t maintain Non-abstract methods.

Example 1

<?php  
    interface a  
    {  
        public function dis1();  
    }  
    interface b  
    {  
        public function dis2();  
    }  
  
class demo implements a,b  
{  
    public function dis1()  
    {  
        echo "method 1...";  
    }  
    public function dis2()  
    {  
        echo "method2...";  
    }  
}  
$obj= new demo();  
$obj->dis1();  
$obj->dis2();  
  
?>  

Output:

method 1…method 2…

Example 2

  

<?php  
    interface i1  
    {  
        public function fun1();  
    }  
    interface i2  
    {  
        public function fun2();  
    }  
class cls1 implements i1,i2  
{  
    function fun1()  
    {  
        echo "protutorials";  
    }  
    function fun2()  
    {  
        echo "tech";  
    }  
}  
$obj= new cls1();  
$obj->fun1();  
$obj->fun2();  
  
?>

Output:

protutorialstech

JavaScript Document Object

JavaScript Document object is an object that provides access to all HTML elements of a document. When an HTML document is loaded into a browser window, then it becomes a document object.

The document object stores the elements of an HTML document, such as HTML, HEAD, BODY, and other HTML tags as objects.

A document object is a child object of the Window object, which refers to the browser.

You can access a document object either using window.document property or using object directly.

See, What we can do with Document Object:

  • Suppose you have created a FORM in an HTML document using the FORM element and added some text fields and Buttons on the Form. On Submitting the Form you want to validate the input or display input on another page. In this situation, you can use a document object which is a child object of the window object. Using the document object, you can access the elements of the form and validate the Input.
  • The Document Object provides different collection elements, such as anchor and Links which helps you to count the number of specific elements on a form.
  • The Document Object also provides various properties such as URLbgcolor, etc. which will allow you to retrieve the details of a document and various methods such as open()close()write(), getElementById()getElementByName(), etc. which allow you to perform various tasks like opening an HTML document to display output and writing a text on Web Page.
  • The Document Object also allows you to create cookies for a webpage by providing a property named cookie. A cookie stores information about the user’s computer, which helps in accessing visited websites.

Now let’s explore document object methods and properties.

JavaScript Document Object Properties

As we know, a property of an object is the value associated with the object. The property is accessed by using the following notation:

objectName.propertyName

where objectName is the name of the object and propertyName is the name of its property.

Now we will show you the properties of document object in the table given below:

PropertiesDescription
cookiereturns a report that contains all the visible and unexpired cookies associated with the document
domainreturns the domain name of the server from which the document has originated
lastModifiedreturns the date on which document was last modified
documentModereturns the mode used by the browser to process the document
readyStatereturns the loading status of the document.
referrerreturns the URL of the documents referred to in an HTML document
titlereturns the name of the HTML document defined between the starting and ending tags of the TITLE element
URLreturns the full URL of the HTML document.

Let’s take an example, to see the document object properties in action:


JS Document Methods Example

Document Methods Example

    <script>
        // Open document
        document.open();
        // writing
        document.write("Hello" +"<br>");
        document.getElementById("demo").innerHTML = "Set by ID";
    </script>
</body>

JavaScript Document Object Methods

JavaScript Document object also provides various methods to access HTML elements.

Now we will show you some of the commonly used methods of the document object:

MethodsDescriptionSyntax
open()opens an HTML document to display the outputdocument.open(mimetype, replace)
close()closes an HTML documentdocument.close()
write()Writes HTML expressions or JavaScript code into an HTML documentdocument.write(exp1, exp2, ...)
writeln()write a new line character after each HTML expressions or JavaScript Codedocument.writeln(exp1, exp2, ...)
getElementById()returns the reference of first element of an HTML document with the specified id.document.getElementById(id)
getElementByName()returns the reference of an element with the specified namedocument.getElementsByName(name)
getElementsByTagName()returns all elements with the specified tagnamedocument.getElementsByTagName(tagname)

Now let’s take an example, to see the document object methods like open()write(), and getElementById() to explain their usage. See the below example:

It Will change

    <script>
        // Open document
        document.open();
        // writing
        document.write("Hello" +"<br>");
        document.getElementById("demo").innerHTML = "Set by ID";
    </script>
</body>

JavaScript Screen Object

JavaScript Screen is a built-in Interface (object type) that is used to fetch information related to the browser screen on which the current window is rendered.

It provides information about the dimensions of the display screen such as its height, width, color bits, etc.

Since the window object is at the top of the scope chain, the property window.screen gives the Screen object, but the screen object can be accessed without specifying the window too, in that case JavaScript automatically detects the browser window, which is created by JavaScript Runtime Engine.

Let’s take a simple example to see the working of the screen object.
JS Screen Object Example

JavaScript Screen Object

    <script>
        document.writeln("Total Height: " + screen.height +"<br>");
        document.writeln("Total Width: " + screen.width +"<br>");
    </script>
</body>

JavaScript Screen Object Properties

JavaScript Screen object includes some properties that are used to get browser screen information. A table of such properties is given below.

PropertyDescription
availHeightspecifies the height of screen, excluding the windows taskbar
availWidthspecifies the width of the screen, excluding the Windows taskbar
colorDepthspecifies the depth of color palette, in bits, to display images
heightspecifies the total height of the screen
pixelDepthspecifies the color Resolution, in bits per pixel, of the screen
widthspecifies the total width of the screen

The Screen object colorDepth property is the number of bits used to represent the color of a single pixel. It returns the bit depth of the color palette for displaying images.

JavaScript Screen Object Methods

There are no direct methods in the Screen method object.

Uses of Screen Object

The JavaScript Screen object can be used for improving the user experience by controlling the UI of the web app or website based on the screen size.

JavaScript Location Object

JavaScript Location is a built-in Interface (object type) which represents the location (URL) of the object to which it is attached. Both the Window object and the Document object have this property. The window objects location property gives us access to the browser window’s location whereas the document location property gives us the location object for a particular document.

It is used to fetch information of the current URL. The Location object allows you to navigate to another webpage as well.

Get Website Host name

    <script>
         var x = location.hostname;
        document.write(x);

    </script>
</body>

There are many different properties of the location object and many methods too.

JavaScript Location Object Properties

JavaScript Location Object has many properties using which we can access the various components of a webpage’s URL and even change it.

Here are some commonly used properties for the location object:

PropertyDescription
hrefRepresents a string specifying the entire URL, for instance
protocolRepresents a String at the begining of a URL to the first colon(:),which specifies the Method of access to the URL , for instance http: or https:
hostRepresents a String consisting of hostname and port Strings,for instance:- http://www.javascriptstudytonight.com:80
hostnameRepresents the server name, subdomain, and domain name (or IP address)of a URL, for instance http://www.javascriptstudytonight.com
portRepresents a string specifying the communication port that the server uses, for instance 80
pathnameRepresents a String Portion of a URL, specifying how a particular resource can be accessed, for instance: order.cgi
searchRepresents a string beginning with a question mark that specifies any query information in an HTTP URL, for instance batch=1
hashRepresents a string beginning with a hash(#), which specifies an anchor name in an HTTP URL, for instance #intro

Let’s take an example and get to know about the properties of Location object.

Location Properties

    <script>
        // Hostname
        let x = location.hostname;
        document.write(x +"<br>");
        // href
        x = location.href;
        document.write(x +"<br>");
        // protocol
        x = location.protocol;
        document.write(x +"<br>");
        // host
        x = location.host;
        document.write(x +"<br>");
        // pathname
        x = location.pathname;
        document.write(x +"<br>");
    </script>
</body>

Now let’s see the methods of the location object.

JavaScript Location Object Methods

Location Object methods refers to the functions created inside the location interface which can be used to perform various operations on the URL like reload it, change it, etc.

MethodDescription
assign()Loads a new Document in the Browser
reload()Reloads the current document that is contained in location.href property.
replace()Replaces the current document with the specified new one. In addition, you cannot navigate back to the previous document using the Browser’s back button.

To load a new document, We can use the assign() method of Location object. But in this example, we have used the href property and the replace() methods too. They all can be used to load a document.

Location Methods example

    <button onclick="load1()">visit studytonight.com</button>
    <button onclick="load2()">visit studytonight.com</button>
    <button onclick="load3()">visit studytonight.com</button>

    <script>
        // assign method
        function load1(){
            location.assign("https://www.studytonight.com");
        }

        // href
        function load2(){
            location.href="https://www.studytonight.com";
        }

        // replace()
        function load3(){
            location.replace("https://www.studytonight.com");
        }

    </script>
</body>

JavaScript Navigator Object

JavaScript Navigator Object is used to fetch information related to the browser(useragent), like the browser name, browser version, operating system information, etc.

JavaScript Navigator object is also a property of the JavaScript Window object and can be accessed using the read only property window.navigator for the current browser window.

In JavaScript, the Navigator Object includes some properties and methods which help us to navigate from one element to another.

Navigator Object Properties

The properties of the navigator object are the variables created inside the Navigator Object.

We can access Navigator Object Property as: navigator.propertyname where propertyname is the name of property.

PropertiesDescription
appcodenamespecifies the code name of the browser (experimental property – can return incorrect value)
appnamespecifies the name of the browser (experimental property – can return incorrect value)
appversionspecifies the version of browser being used (experimental property – can return incorrect value)
cookieEnabledspecifies whether cookies are enabled or not in the browser
platformcontains a string indicating the machine type for which the browser was compiled.
useragentcontains a string representing the value of user-agent header sent by the client to server in HTTP protocol
geolocationreturns object of GeoLocation which can be used to get the location information of the device.
onLinespecifies whether the browser is online or not.
languagereturns a string with the preferred browser language, for example, en-US for English.
languagesreturns a string with all the languages supported by the browser in order of user preference.

There are some more expreimental properties available in the Navigator object, but the ones mentioned above are most commonly used properties.

Navigator Object Example

    <script>
        let appc =  navigator.appCodeName;
        let appn =  navigator.appName;
        let appv =  navigator.appVersion;
        let appco = navigator.cookieEnabled;
        let lan   = navigator.language;
        let onl = navigator.onLine;
        let pla = navigator.platform;
        let usra = navigator.userAgent;

        document.write(appc +"<br>");
        document.write(appn +"<br>");
        document.write(appv +"<br>");
        document.write(appco +"<br>");
        document.write(lan +"<br>");
        document.write(onl +"<br>");
        document.write(pla +"<br>");
        document.write(usra +"<br>");
    </script>

</body>

Navigator Object Methods

The Navigator object doesn’t have many standardised methods, most of the methods available are experimental.

Method NameDescription
registerProtocolHandler()allows websites to register themselves as protocol handler so that they are allowed to open some standard URL schemes like mailto:tel:sms:, etc,
share()used to utilize the native support of sharing available in browser.
sendBeacon()used to send a small data packet from the client to the server
vibrate()if supported, this can be used to make the device vibrate, if not supported, nothing happens. This is useful in mobile browsers.

Use of Navigator Object:

The navigator object can be used for multiple specific usecases which can help you make your website better, like:

  1. Making you web app or website more compatible with different browsers by writing specific code for different browsers to resolve compatibility issues.
  2. You can check if the browser is online or not, to show some message if the browser is disconnected from internet.
  3. You can use the location information of the user to show location specific content.
  4. You can set the preferred language as the website language if you support multiple languages on your website.

All the points mentioned above can improve the user experience of your website multifold.

JavaScript History Object

JavaScript History is a built-in Interface (object type) which is used to access the browser window session history. It contains the list of URLs visted by a user in a particular browser window, tab or frame, represented by the window object.

The history object is a property of the JavaScript window object, and can be accessed through the window.history property, and is used to access the session history for that window object.

It provides useful methods and properties that let us navigate back and forth through the window’s session history.

Let’s take an example to see how this works to understand it better.

JavaScript History Object Example

The History object’s back() method is used to go back to the previous URL accessed in the browser window, in the history list.

It is same as clicking the “Back button” in your browser.

<button onclick="goBack()">Go Back</button>

<script>
	function goback(){
	    window.history.back();
	}
</script>

Similarly, we can use the history object’s forward() method to load the next URL in the history list. If next URL is not present, it does nothing.

It is same as clicking the “Forward button” in your browser.

<button onclick="goforward()">Go Forward</button>

<script>
	function goforward(){
	    window.history.forward();
	}
</script>

Apart from the back() and forward(), JavaScript history object provides more methods like go()which can be used to jump to any specific URL present in the history object.

To move to any specific page, we can use the go() method, it takes an integer argument that works as an index value for history URL list. See the below example:

<script>
    // move to one page backward
	window.history.go(-1);

    // move to two page backward
    window.history.go(-2);

    // move to one page forward
    window.history.go(1);

    // move to two page forward
    window.history.go(2);
</script>

We can also use the go() method of history object to refresh the current page. In the example below, we have called the go() method two times and it works the same in the both scenario. We can call it anytime when we want to refresh/reload the current page.

<script>
// Refresh the page
        window.history.go(0);

        window.history.go();

</script>

JavaScript History Object Property

Following are the properties of the History object. The length property is used the most.

PropertiesDescription
lengthspecifies the number of elements contained in the object
scrollRestorationallows web applications to explicitly set default scroll restoration behavior on history navigation
staterepresents the state at the top of the history stack

Let’s take an example to get number of pages visited by a user in a browser window. We will use the length property that contains information for the visited pages.

JavaScript History Object Methods

JavaScript History object methods refer to the functions created inside the history object. These methods specify the actions related to the URLs visited in the Browser window’s current session.

MethodsDescription
back()specifies a method that loads the previous URL from the history list.
forward()specifies a method that loads the next URL from the history list.
go()specifies a method that loads a specific URL from the history list.
pushState()used to push the given data onto the session history stack with the specified title
replaceState()used to update the most recent entry on the history stack to the specified data, title, and, if provided, URL

We have explained each method with examples in the beginning of this tutorial itself.

In the next tutorial we will learn about the Navigator browser object.

JavaScript User-defined Object Type

This tutorial covers the concept of the user-defined object type in JavaScript. We have already covered JavaScript object which is created using object initializer syntax or the Object constructor syntax, and instance of an Object type is created.

Just like the default Object type, using which we can create objects in JavaScript, we can define our custom type using which we can create custom objects in JavaScript.

Creating User-defined JavaScript Object Type

We can define a custom object type by writing a constructor function where the name of the function should start with an uppercase alphabet for example CarCupHuman, etc.

The constructor function is defined just as we define any other user-defined JavaScript Function.

Here is the syntax for defining a constructor function:

function Xyz(param1, param2, ... , paramN)
{
    this.param1 = param1;
    this.param2 = param2;
    ...
    this.paramN = paramN;    
}

Once we have the constructor function defined, we can use it to create an object using the new keyword as follows:

let customObj = new Xyz(paramValue1, paramValue2, paramValue3, ... , paramValueN);

Using this Keyword

In JavaScript we use this keyword to reference the current object, hence in the constructor function we create new properties (param1param2, …) for the object type and we set the values for the parameters provided at the time of object creation using the new keyword.

Few Points to Remember:

  1. We can update the constructor function as many times we want, adding more properties or removing properties from it.
  2. We can also store another object in an object’s property while creating the object uwing the new keyword.
  3. We can use default parameters to specify default values and Rest parameters while defining a user-defined object type’s constructor function.

Now let’s take a few examples to see how we can define a custom object type and create an object using the new keyword.

User-defined JavaScript Object Type Example

In the below code example we have created a new constructor function for object type Bike, and then created an object using the new keyword.

<!-- wp:paragraph -->
<p>This tutorial covers the concept of the user-defined object type in JavaScript. We have already covered&nbsp;JavaScript object&nbsp;which is created using&nbsp;<strong>object initializer syntax</strong>&nbsp;or the&nbsp;<strong>Object constructor</strong>&nbsp;syntax, and instance of an&nbsp;<code>Object</code>&nbsp;type is created.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Just like the default Object type, using which we can create objects in JavaScript, we can define our custom type using which we can create custom objects in JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Creating User-defined JavaScript Object Type</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We can define a custom object type by writing a constructor function where the name of the function should start with an uppercase alphabet for example&nbsp;<em>Car</em>,&nbsp;<em>Cup</em>,&nbsp;<em>Human</em>, etc.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The constructor function is defined just as we define any other user-defined&nbsp;JavaScript Function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is the&nbsp;<strong>syntax for defining a constructor function</strong>:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">function Xyz(param1, param2, ... , paramN)
{
    this.param1 = param1;
    this.param2 = param2;
    ...
    this.paramN = paramN;    
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Once we have the constructor function defined, we can use it to create an object using the&nbsp;<code>new</code>&nbsp;keyword as follows:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let customObj = new Xyz(paramValue1, paramValue2, paramValue3, ... , paramValueN);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:heading {"level":3} -->
<h3>Using&nbsp;<code>this</code>&nbsp;Keyword</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In JavaScript we use&nbsp;<code>this</code>&nbsp;keyword to reference the current object, hence in the constructor function we create new properties (<em>param1</em>,&nbsp;<em>param2</em>, ...) for the object type and we set the values for the parameters provided at the time of object creation using the&nbsp;<code>new</code>&nbsp;keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Few Points to Remember:</h3>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>We can update the constructor function as many times we want, adding more properties or removing properties from it.</li><li>We can also store another object in an object's property while creating the object uwing the&nbsp;<code>new</code>&nbsp;keyword.</li><li>We can use&nbsp;default parameters&nbsp;to specify default values and&nbsp;Rest parameters&nbsp;while defining a user-defined object type's constructor function.</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Now let's take a few examples to see how we can define a custom object type and create an object using the&nbsp;<code>new</code>&nbsp;keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>User-defined JavaScript Object Type Example</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In the below code example we have created a new constructor function for object type&nbsp;<strong>Bike</strong>, and then created an object using the&nbsp;<code>new</code>&nbsp;keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can create as many objects of type Bike once we have defined the constructor function for it. We can set different property values while creating objects. For example,</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let myBike = new Bike("KTM", "Duke", 2020);
let yourBike = new Bike("Royal Enfield", "Classis", 2020);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>We can compare these objects using JavaScript operators and perform a lot of other operations too.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Using a user-defined Object as Property of another Object</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's define one more object type and then use it as a value in our&nbsp;<strong>Bike</strong>&nbsp;object type.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We have defined a new object type&nbsp;<strong>Person</strong>&nbsp;below, and have also added a new property&nbsp;<strong>owner</strong>&nbsp;in the&nbsp;<strong>Bike</strong>&nbsp;object type in which we will store the&nbsp;<strong>Person</strong>&nbsp;objects.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can do anything with user-defined object types in JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Using the&nbsp;<code>Object.create</code>&nbsp;method</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you do not want to get into the trouble of defining a constructor method to define a user-defined object type, you can use the Object.create() method to create an object of any prototype object which is already defined.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take an example to understand this.</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let Bike = {
    company: 'KTM',  // Default value of properties
    model: 'Duke 390',
    show: function() {  // Method to display property type of Bike
        document.write(this.company+" "+this.model);
    }
};

// using Object.create to create a new object
let newBike = Object.create(Bike);
newBike.company = 'Yamaha';
newBike.model = 'R15';
newBike.show();</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Yamaha R15</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As you can see in the code above, we can use the&nbsp;<code>Object.create</code>&nbsp;method to create a new object using an already defined object, and then if required we can change the properties values and use the object function too.</p>
<!-- /wp:paragraph -->

<!-- wp:buttons -->
<div class="wp-block-buttons"><!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link" href="https://wp.me/pc22El-Vx">< prev</a></div>
<!-- /wp:button -->

<!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link" href="https://wp.me/pc22El-VP">next ></a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->

We can create as many objects of type Bike once we have defined the constructor function for it. We can set different property values while creating objects. For example,

let myBike = new Bike("KTM", "Duke", 2020);
let yourBike = new Bike("Royal Enfield", "Classis", 2020);

We can compare these objects using JavaScript operators and perform a lot of other operations too.

Using a user-defined Object as Property of another Object

Let’s define one more object type and then use it as a value in our Bike object type.

<!doctype html>
	<head>
		<title>Object in Object Example JavaScript</title>
	</head>
	<body>
		<script>
			/* defining a new constructor function */
			function Person(name, age, city) {
                this.name = name;
                this.age = age;
                this.city = city;
            }
            
            function Bike(company, model, year, owner) {
                this.company = company;
                this.model = model;
                this.year = year;
                this.owner = owner;
            }
            
            /* creating the object */
            let john = new Person("John Wick", 30, "New York");
            let myBike = new Bike("KTM", "Duke", 2010, john);
            
            document.write(myBike.company+"<br/>"+myBike.model+"<br/>"+myBike.year+"<br/>"+myBike.owner.name);
		</script>
	</body>
</html>

We have defined a new object type Person below, and have also added a new property owner in the Bike object type in which we will store the Person objects.

We can do anything with user-defined object types in JavaScript.

Using the Object.create method

If you do not want to get into the trouble of defining a constructor method to define a user-defined object type, you can use the Object.create() method to create an object of any prototype object which is already defined.

Let’s take an example to understand this.

let Bike = {
    company: 'KTM',  // Default value of properties
    model: 'Duke 390',
    show: function() {  // Method to display property type of Bike
        document.write(this.company+" "+this.model);
    }
};

// using Object.create to create a new object
let newBike = Object.create(Bike);
newBike.company = 'Yamaha';
newBike.model = 'R15';
newBike.show();

Yamaha R15

As you can see in the code above, we can use the Object.create method to create a new object using an already defined object, and then if required we can change the properties values and use the object function too.