Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Javascript proxies – restricting access to object properties and some other practical examples

Let's say we want to create a Javascript object that has some restricted private fields. We will consider them as private if their name stars with the _ character.

This means that if we have the following object:

let bankAccount = {
    holderName: 'Joe',
    currency: 'USD',
    _balance: 1000
}

We want to restrict any access to operations like:

// don't allow reading the balance
console.log(bankAccount._balance);
// don't allow deleting the property
delete _balance

Well, this is a perfect place to use the Javascript proxies. By the way, I've written a short intro about what Javascript proxies are here.

First, we will define the implementation of the proxy:

let proxyHandler = { 
    has: (target, prop) => { 
        if(prop.startsWith(prefix)){ 
            return false;
        } 
        return prop in target 
    }, 
    ownKeys: target => { 
        return Reflect.ownKeys(target).filter( 
            prop => !prop.startsWith(prefix) 
        ) 
    }, 
    get: (target, prop) => { 
        if(prop.startsWith(prefix)) { 
            return undefined; 
        } 
        return target[prop]; 
    }, 
    deleteProperty(target, prop) { 
        if (prop.startsWith('_')) { 
            return true; 
        } else { 
            delete target[prop]; 
            return true; 
        }
    }
}

And to see it in action:

const hidePrivateFields = (target, prefix = "_") => { 
    return new Proxy(target, proxyHandler)
};

let bankAccount = hidePrivateFields({
    holderName: 'Joe',
    currency: 'USD',
    _balance: 1000
})

bankAccount._balance // undefined 
('_password' in userInfo) // false 
Object.keys(bankAccount) // ['holderName', 'currency'] 
delete bankAccount._balance // returns true, but does not delete the balance

I've found other cool practical examples of using Javascript proxies:

  • in this article written by Tobias Ahlin about how we can use proxies to chain multiple styles changes like style(".menu").color("#fff").backgroundColor("#000").opacity("1");
  • and in this CSS tricks article were we can see them used to do some cool UI stuff
Home Screencasts Best of Newsletter Search X