码迷,mamicode.com
首页 > 数据库 > 详细

[Javascript] Customize Behavior when Accessing Properties with Proxy Handlers

时间:2019-05-31 23:36:51      阅读:152      评论:0      收藏:0      [点我收藏+]

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

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.

 

"use strict"

let person = {
  name: "John"
}

let handler = {
  get(target, key) {
    if (key === "name") {
      return "Mindy"
    }

    if (Reflect.has(target, key)) {
      return Reflect.get(target, key)
    }

    return "You tried to access something undefined"
  }
}

person = new Proxy(person, handler)

console.log(person.name) // "Mindy"
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   

原文地址:https://www.cnblogs.com/Answer1215/p/10957810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!