การเข้าถึงฟังก์ชันเป็นเมธอด
ออบเจ็กต์จาวาสคริปต์ประกอบด้วยคุณสมบัติ ในการเข้าถึงคุณสมบัติเป็นเมธอด เพียงแค่กำหนดฟังก์ชันให้กับคุณสมบัติและรวมคุณสมบัติอื่นๆ ในฟังก์ชันนั้นด้วย
ในตัวอย่างต่อไปนี้ อ็อบเจ็กต์ชื่อ "employee" จะถูกสร้างขึ้นด้วยคุณสมบัติ "fullName", "lastName" , "firstName" และ "id" ฟังก์ชั่นถูกกำหนดภายใต้คุณสมบัติ "fullName" และคุณสมบัติเช่น "firstName" และ "lastName" รวมอยู่ในนั้น ดังนั้นเมื่อมีการเรียกคุณสมบัติ "fullName" ชื่อเต็มของพนักงานจะแสดงตามที่แสดงในผลลัพธ์
ตัวอย่าง-1
<html>
<body>
<script type="text/javascript">
var employee = {
firstName: "raju",
lastName : "nayak",
Designation : "Engineer",
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
document.write(employee.fullName());
</script>
</body>
</html> ผลลัพธ์
raju nayak
ตัวอย่าง-2
<html>
<body>
<script type="text/javascript">
var student= {
Name: "susan",
country : "USA",
RollNo : "5",
details : function() {
return "the student named" + " " + this.Name + " " +"is allocated with rollno " + " " + this.RollNo ;
}
};
document.write(student.details());
</script>
</body>
</html> ผลลัพธ์
the student named susan is allocated with rollno 5