Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách hoạt động của JavaScript .prototype

Đối tượng trong JavaScript kế thừa thuộc tính và phương thức từ prototype của chúng. Tạo object bằng new Object() cũng kế thừa từ Object.prototype. Tương tự, new Date() kế thừa Date.prototype.

Ví dụ

<!DOCTYPE html>
<html>
  <body>
    <h2>Department Details</h2>
    <p id="details"></p>
    <script>
      function Department(myid, name, section) {
        this.id = myid;
        this.name = name;
        this.section = section;
      }
      var myDept = new Department("AKD", "Marketing", "North");
      document.getElementById("details").innerHTML = 
        "The name and section of the Department is " + myDept.name + " and " + myDept.section + " respectively.";
    </script>
  </body>
</html>

Mở rộng: Thêm phương thức vào prototype: Department.prototype.getInfo = function() {...}. Tất cả instance sẽ chia sẻ phương thức này (tiết kiệm bộ nhớ). ES6 class là syntactic sugar trên prototype.