如何在 JavaScript 中将函数属性作为方法访问?
javascriptobject oriented programmingprogramming
将函数作为方法访问
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