การเข้าถึงฟังก์ชันเป็นเมธอด
JavaScript object ประกอบด้วย properties เพื่อเข้าถึง property เป็นเมธอด ให้กำหนดฟังก์ชันให้ property นั้นและรวม property อื่นๆ ไปในฟังก์ชันนั้น
ตัวอย่าง: สร้างออบเจ็กต์ "employee" มี properties: fullName, lastName, firstName, id กำหนดฟังก์ชันที่ property "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