js-mentorship-razvan / javascript

Javascript study notes
GNU General Public License v3.0
22 stars 2 forks source link

Create a proxy that takes the object above and when it's being read like proxyUser.firstName #460

Closed odv closed 4 years ago

odv commented 4 years ago

const user = { firstName: 'John', lastName: 'Doe', email: 'john.doe@example.com', }

// it should return :
// Property firstName has been read.
// "John"
RazvanBugoi commented 4 years ago

We cannot reassign a constant variable.

But, if the variable was defined with 'let' instead of 'const', I would do something like this :

user = new Proxy(user, {
    get(target, prop) {
        if(prop in target) {
            return `Property firstName has been read. \n ${target[prop]}`;
        } else {
            return 'Property you are looking for does not exist.';
        }
    }
});