如何在JavaScript中将函数属性作为方法访问?
作为方法访问函数
一个javascript对象由属性组成。要将属性作为方法进行访问,只需将一个函数定义为一个属性,然后在该函数中包含其他属性。
在下面的示例中,创建了一个名为“员工”的对象,其属性为“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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短