Explain Native Prototypes in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

The prototype property is the core part of javaScript as JavaScript is a prototype-based language. Prototypes are used to implement inheritance in JavaScript. All the custom and built in native objects have the prototype property which can be used to extend their functionality by adding new properties and methods to them. The native prototypes can only be edited or new ones can be added to them but they can’t be deleted.

Following is the code for native prototypes in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Native Prototypes in JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to convert the above string to alternate case using prototype
</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let BtnEle = document.querySelector(".Btn");
   String.prototype.alternateCase = function () {
      let newString = "";
      for (let i = 0; i < this.length; i++) {
         if (i % 2 == 0) {
            newString += this[i].toUpperCase();
         }
         else {
            newString += this[i].toLowerCase();
         }
      }
      return newString;
   };
   let a = "HELLO WORLD";
   sampleEle.innerHTML += a;
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML += a.alternateCase();
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 17-Jul-2020 08:28:43
Advertisements