Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Customize Behavior when Accessing Properties with Proxy Handlers

    John LindquistJohn Lindquist

    A 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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 0:00 When we log out person.name, the log will show John. We can hijack that process by assigning person to a new proxy. Pass in person and a handler, and we can define our handler to implement a get function.

    0:22 Now if I always return something, then when I log out person.name, I'll get back something. Whatever I return from here will be assigned to the property I'm trying to access, regardless if that property exists or not.

    0:41 Age is not defined, but because I'm trying to get a property off of person, age returns as whatever instead of undefined. If I remove the proxy, you can see John and undefined. If I put the proxy back, you can see whatever and whatever.

    0:56 The arguments for the get function are the target and the key, the target being the person object and the key being whichever property return access. If we log those out, console log target and key, we'll see John name and John age.

    1:16 If we just want the default behavior, we can just reflect get target key, and we'll get John and undefined as expected.

    1:26 This does give us the opportunity to modify the returned result. I could say plus, exclamation point, where we always have an exclamation point, add it to the end of whatever's returned, or you can check if the key is a specific thing.

    1:41 If the key is name, I always want to return Mindy. You can see it returns Mindy rather than checking what's on the actual target.

    1:51 You can also handle this undefined scenario. You could say if reflect has target key, then return the actual result. Otherwise, return "You tried to access something undefined." Hit save and you can see Mindy comes through just fine. Person age comes through as "You tried to access something undefined."

    2:21 You have lots of options on how to handle accessing properties off the objects.