当前位置:Gxlcms > 数据库问题 > [Javascript] Customize Behavior when Accessing Properties with Proxy Handlers

[Javascript] Customize Behavior when Accessing Properties with Proxy Handlers

时间:2021-07-01 10:21:17 帮助过:3人阅读

Proxy allows you to trap what happens when you try to get a property value off of an object and do some behavior before the value is accessed. For example, you could check the name of the property and always return a certain value or even check if the property is undefined and return some default. The options are unlimited.

 

  1. "use strict"
  2. let person = {
  3. name: "John"
  4. }
  5. let handler = {
  6. get(target, key) {
  7. if (key === "name") {
  8. return "Mindy"
  9. }
  10. if (Reflect.has(target, key)) {
  11. return Reflect.get(target, key)
  12. }
  13. return "You tried to access something undefined"
  14. }
  15. }
  16. person = new Proxy(person, handler)
  17. console.log(person.name) // "Mindy"
  18. console.log(person.age) // "You tried to access something undefined"

  

[Javascript] Customize Behavior when Accessing Properties with Proxy Handlers

标签:str   obj   could   let   name   code   amp   check   prope   

人气教程排行