Search code examples
javascriptobjectecmascript-6default-valueecmascript-next

How I can set general getter for an existing object?


I'm interested in adding common getter which would executes on every property get call of an existing object. All we know how to set getter for specific property, but can we set getter which's callback would be involved during getting every property in an object?

Thank you very much.


Solution

  • I think you're thinking of a Proxy.

    Specifically, you can use the handler.get() to intercept any property.

    Example

    const guitar = {
      stringCount: 6,
      model: 'Stratocaster',
    };
    
    // this is where the magic happens
    const genericHandler = {
      get: function(target, propertyName) {
        // at this point, you can do anything you want – we'll just log the attempt
        console.log(`Attempted to get ${propertyName}`);
    
        // this will return the original value
        return target[propertyName];
      }
    };
    
    const proxiedGuitar = new Proxy(guitar, genericHandler);
    
    // This outputs
    //   Attempted to get stringCount
    //   6
    console.log(proxiedGuitar.stringCount);
    
    // you can even write a handler for non-existent properties
    console.log(proxiedGuitar.pickupType);
    

    This is a simplified and incomplete example which may not work in some cases. See @loganfsmyth's clarification in the comment below.