当访问属性时,该值通过隐式调用函数获得。get关键字在JavaScript中使用。可以设置一个标识符,可以是数字或字符串。
设置属性后,它将隐式调用函数,并将值作为参数传递。这样,返回值将设置为属性本身。set关键字在JavaScript中使用。可以设置一个标识符,可以是数字或字符串。
这是显示如何同时实现getter和setter的示例
<html> <body> <script> var department = { deptName: "Marketing", deptZone: "North", deptID: 101, get details() { return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID; }, set details(info) { var words = info.toString().split(' '); this.deptName = words[0] || ''; this.deptZone = words[1] || ''; this.deptID = words[2] || ''; } } department.details = 'Marketing North 001'; document.write(department.deptName); document.write(department.deptZone); document.write(department.deptID); </script> </body> </html>