Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript .prototype ทำงานอย่างไร?

Object ใน JavaScript สืบทอด Property และ Method จาก Prototype ของมัน สร้างด้วย new Object() จะสืบทอดจาก Object.prototype สร้างด้วย new Date() จะสืบทอดจาก Date.prototype

ตัวอย่าง

<!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>