Intercept property access with Javascript Proxy

Khaled Garbaya
InstructorKhaled Garbaya
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

A Javascript Proxy object is a very interesting es6 feature, that allows you to determine behaviors whenever a property is accessed in a target object. In this lesson, you will learn how to use it to prevent users from accessing specific properties in your objects

Instructor: [00:00] We have here a test project using Jest in watch mode. Currently, it's passing because there is no test case in here. What I want to do is to intercept the access to any property that starts with underscore and treated as private. We can do that using a proxy.

[00:20] Let's add our first test case. We expect here that we will throw whenever we try to access the underscore ID. If we save, you can see our tests are failing, on the right.

[00:35] To intercept the get access in the proxy object, we need to define the get inside the handler. The get function will accept the target and the property, and will check if the first character is underscore, we throw. Otherwise, we return the property value.

[00:53] If we save now, you can see our test is passing. Now, let's try to test setting the underscore ID. We expect trying to set the underscore ID here to throw an error. If we save, you can see our tests are failing.

[01:11] To fix that, we need to define the set trap function. The set trap function will receive targets, the property, and its value. Again, we can do the same check. If it starts with underscore, we throw an error. Otherwise, we set the new value and return true. This is important for proxies.

[01:32] If we save now, you can see that our test is passing. In review, we use JavaScript proxy object to intercept access to all the properties in our object and check if any property has an underscore, we'll treat it as private.

egghead
egghead
~ 14 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today