Blogger Information
Blog 94
fans 0
comment 0
visits 92417
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】JS之访问器属性:方法改属性
可乐随笔
Original
550 people have browsed it

访问器属性

普通写法

  1. let course = {
  2. lesson: {
  3. name: 'ES6',
  4. score: 60,
  5. },
  6. //读取接口
  7. getScore() {
  8. return {
  9. name: this.lesson.name,
  10. course: this.lesson.score,
  11. }
  12. },
  13. //设置接口
  14. setScore(score) {
  15. //设置接口一般都要写验证
  16. if (score >= 0 && score <= 100) {
  17. this.lesson.score = score
  18. } else {
  19. console.log('成绩必须在1-100分之间')
  20. }
  21. },
  22. }
  23. console.log(course.lesson.name)
  24. console.log(course.getScore())
  25. course.setScore(80)
  26. console.log(course.getScore())
  27. console.log('-----------------------')

用户习惯

  1. //console.log(course.score)
  2. //course.score = 90
  3. // ? 使用“访问器属性”就可以实现
  4. course = {
  5. lesson: {
  6. name: 'ES6',
  7. score: 60,
  8. },
  9. score: 99,
  10. //getScore ===> get score
  11. //普通方法 ===> 访问器属性
  12. //如果使用访问器属性,get必须要有,set可选
  13. get score() {
  14. return {
  15. name: this.lesson.name,
  16. course: this.lesson.score,
  17. }
  18. },
  19. //将一个方法,伪装成“属性”
  20. set score(score) {
  21. //设置接口一般都要写验证
  22. if (score >= 0 && score <= 100) {
  23. this.lesson.score = score
  24. } else {
  25. console.log('成绩必须在1-100分之间')
  26. }
  27. },
  28. }
  29. console.log(course.score)
  30. course.score = 90
  31. console.log(course.score)

访问器属性优先级大于同名属性

对象中有同名属性score,也有访问器属性get score和set score

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!