Intercept property access with Javascript Proxy

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

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.