Blogger Information
Blog 46
fans 0
comment 0
visits 34462
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
访问器属性原理及应用场景
上草一方
Original
410 people have browsed it

访问器属性

属性访问器提供了两种方式用于访问一个对象的属性,它们分别是点号和方括号。
语法为:object.property 和 object[‘property’]

实例代码如下:

  1. const person1 = {};
  2. person1['firstname'] = 'Mario';
  3. person1['lastname'] = 'Rossi';
  4. console.log(person1.firstname);
  5. // expected output: "Mario"
  6. const person2 = {
  7. firstname: 'John',
  8. lastname: 'Doe'
  9. };
  10. console.log(person2['lastname']);
  11. // expected output: "Doe"

应用实例代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>访问器属性</title>
  8. </head>
  9. <body>
  10. <script>
  11. // 访问器属性
  12. let user={
  13. //常规属性
  14. data:{
  15. name:'mary',
  16. age:18,
  17. },
  18. // 获取年龄
  19. getAge(){
  20. return this.data.age;
  21. },
  22. //设置年龄
  23. setAge(age){
  24. if (age>=18 & age<=120){
  25. this.data.age=age;
  26. }else{
  27. console.log('非法数据');
  28. }
  29. },
  30. };
  31. console.log(user.getAge());
  32. user.setAge(80);
  33. console.log(user.getAge());
  34. console.log('----------');
  35. // 对于用户来说,获取年龄,习惯性会用这种方式获取
  36. // console.log(user.age);
  37. // console.log(user.data.age);
  38. user={
  39. //常规属性
  40. data:{
  41. name:'mary',
  42. age:18,
  43. },
  44. //将传统的方法,修改成一个伪装成属性的方法
  45. get age(){
  46. return this.data.age;
  47. },
  48. //设置年龄,将之前的设置方法修改成了一个属性
  49. //方法-->属性:伪装成方法的属性,“访问器属性”
  50. set age(age){
  51. if (age>=18 & age<=120){
  52. this.data.age=age;
  53. }else{
  54. console.log('非法数据');
  55. }
  56. },
  57. };
  58. console.log(user.age);
  59. console.log('----------');
  60. user.age=150;
  61. console.log(user.age);
  62. //访问器属性,本质上还是方法,但是调用的时候还是属性
  63. </script>
  64. </body>
  65. </html>

控制台效果如下:

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post