一个javascript对象由属性组成。要将属性作为方法进行访问,只需将一个函数定义为一个属性,然后在该函数中包含其他属性。
在下面的示例中,创建了一个名为“员工”的对象,其属性为“ fullName”,“ lastName”,“ firstName”和“ id”。函数在属性“ fullName”下定义,并且其中包括“ firstName”和“ lastName”之类的属性。因此,当调用属性“ fullName”时,将显示雇员的全名,如输出所示。
<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
<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