# Proxy & Reflect

## Proxy and Reflect

**Proxy**

Capable of intercepting diverse types of operations in a target object.

Trap methods for diverse `events` related to objects.

* `apply()`
* `construct()`
* `defineProperty()`
* `deleteProperty(target, key)`
  * invoked when a property is deleted.
* `get(target, key)`
  * invoked when a property is accessed.
* `getOwnPropertyDescriptor()`
* `getPrototypeOf()`
* `has()`
* `isExtensible()`
* `ownKeys()`
* `preventExtensions()`
* `set(target, key, value)`
  * invoked when a property is defined in a object.
* `setPrototypeOf()`

*Ex.: Let's try to make a Factory of objects that will act as arrays.*

```javascript
const createArray = function () {
    return {};
}

const arr = createArray();
arr[0] = 'A';
arr[1] = 'B';
arr[2] = 'C';
```

*Let's suppose that we want to implement a way of having a `length`.*

```javascript
const createArray = function () {
    // First object is the object to be trapped.
    // Second object is the Traps definitions.
    return new Proxy({}, {
        set(target, key, value) {
            // This length is a created property to hold the length of elements
            target.length = target.length || 0;
            target.length++;

            // We also have to implement this attribution otherwise the object will not save elements
            target[key] = value;
        },
        get(target, key) {
            // Accept only numbers as keys
            if (typeof key === 'string' && key.match(/\d+/))
                return target[key];
        }
        deleteProperty(target, key) {
            if (key in target) {
                target.length--;
                delete target[key];
            }
        }
    });
}
```
