คลาส
คลาส เป็นประเภทของฟังก์ชัน แต่แทนที่จะใช้คำหลัก 'ฟังก์ชัน ' คำหลัก 'คลาส ' ใช้เพื่อเริ่มต้น และคุณสมบัติถูกกำหนดภายใน constructor() กระบวนการ. คอนสตรัคเตอร์() เมธอดจะถูกเรียกทุกครั้งที่เริ่มต้นคลาสอ็อบเจ็กต์
ตัวอย่าง-1
ในตัวอย่างต่อไปนี้ คลาส เรียกว่า 'บริษัท ' ถูกสร้างขึ้นและอยู่ภายใน constructor() วิธี ชื่อบริษัทที่ได้รับมอบหมายและแสดงผลในผลลัพธ์
<html>
<body>
<p id="class"></p>
<script>
class Company {
constructor(branch) {
this.name = branch;
}
}
myComp = new Company("Tutorialspoint");
document.getElementById("class").innerHTML = myComp.name;
</script>
</body>
</html> ผลลัพธ์
Tutorialspoint
ตัวอย่าง-2
<html>
<body>
<script>
class Company {
constructor(branch) {
this.name = branch;
}
}
myComp = new Company("Rk enterprises");
document.write(myComp.name);
</script>
</body>
</html> ผลลัพธ์
Rk enterprises