如何在 JavaScript 中以一種方法的形式訪問一個函式屬性?
以方法的形式訪問函式
一個Javascript物件由屬性組成。要以方法的形式訪問一個屬性,只需將一個函式定義為屬性並把其他屬性包含在該函式中即可。
在下面的例子中,一個名為“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
廣告