Javascript - Collection Proxy ownKeys

Introduction

Proxy ownKeys is used to trap the access of the owned properties and owned symbol properties via Object.keys(), Object.getOwnPropertyNames() or Object.getOwnSymbolProperties().

This can be used in combination with the has trap handler to strengthen the privacy of the target object properties.

These properties are not be completely private:

Demo

const restaurant = { 
    soda: 5, // ww  w .  jav a2 s.c  om
    beer: 10 
}; 

const restHandler = { 
    has: function(target, property) { 
        if (property === "beer") { 
            return false; 
        } 
        return property in target; 
    }, 

    ownKeys: function(target) { 
        return ["soda"]; 
    } 
} 

const restProxy = new Proxy(restaurant, restHandler); 

console.log("beer" in restProxy);          // false 
console.log(Object.keys(restProxy));       // ["soda"]

Result

You can add another trap handler: getOwnPropertyDescriptor, which traps the Object.getOwnPropertyDescriptor() calls, to enhance the privacy.

Related Topic