Computer >> Máy Tính >  >> Lập trình >> Javascript

Chia sẻ các phương pháp trong JavaScript

Các phương thức có thể được chia sẻ bằng cách gắn chúng vào thuộc tính nguyên mẫu của đối tượng. Các phương thức này sẽ được chia sẻ giữa tất cả các phiên bản của đối tượng.

Sau đây là mã cho các phương pháp chia sẻ trong JavaScript -

Ví dụ

<!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 {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Shared methods in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to the call the displayInfo method of student1 and student2 object</h3>
<script>
   let resEle = document.querySelector(".result");
   function Student(name, age, standard) {
      this.name = name;
      this.age = age;
      this.standard = standard;
   }
   Student.prototype.displayInfo = function () {
      return `${this.name} age ${this.age} : standard :${this.standard} <br>`;
   };
   let student1 = new Student("Rohan", 17, 12);
   let student2 = new Student("Shawn", 16, 11);
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = student1.displayInfo();
      resEle.innerHTML += student2.displayInfo();
   });
</script>
</body>
</html>

Đầu ra

Chia sẻ các phương pháp trong JavaScript

Khi nhấp vào nút 'BẤM VÀO ĐÂY' -

Chia sẻ các phương pháp trong JavaScript