JavaScript proxies: a readonly wrapper factory

EcmaScript 6 (ES6) introduces the Proxy class, which we can use to straightforwardly implement design patterns like (obviously) proxy, decorator and similar.
The only thing we need is to create an instance of Proxy, providing the proxied object/function and a handler object, containing hook methods (the official doc calls them traps) that we can use to intercept and modify the proxied object’s behaviour.

For example, we can intercept and modify calls to object properties’ get calls providing a get(target, prop, handler) function in the handler object, or we can intercept and modify calls to a function providing a apply(target, thisArg, argumentsList) in the handler object.

The list of the supported traps is available here.

Here we use the set trap to simply implement a readonly factory function, which receieves an object and returns a new object wrapping the original object behind a read-only proxy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function readonly(target) {
return new Proxy(target, {
set: function(target, prop, recever) {
throw `Can't set '${prop}': this is a read-only object!`
}
})
}

const original = {
x: 1,
y: [1, "two"]
}

const readOnly = readonly(original)

console.log(readOnly.x) // 1
console.log(readOnly.y) // Array [ 1, "two" ]

original.x = 19
console.log(readOnly.x) // 19

readOnly.x = 11 // Uncaught Can't set 'x': this is a read-only object!