The Proxy object enables you to create a proxy for another object... (MDN)
Ok, we understand: Proxies are one of the more exotic language features of Javascript, that are seemingly not so easy to explain. But they enable a clever and sometimes handy design pattern I want to introduce here.
Using smart destructuring
Simply spoken, a proxy can change the behavoir of an object: proxy functions can be invoked if properties are set or read, which is often used to change or limit values. But we can also introduce a completely new behavoir. This is used in the following code:
const extract = (arg) => new Proxy({}, {
get: (obj, prop) => {
let ret = arg[prop]
delete ar[prop]
return ret
}
})
let ar = { a: 1, b: 2, c: 3, d: 4 }
let { a, b } = extract(ar) // extract a and b
console.log(a) // => 1
console.log(b) // => 2
console.log(ar) // => {c: 3, d: 4}
The example above gets a and b from the array ar
using destructuring, but it not only reads a and b, but removes them from the object. How can we use this? Here is an example that packs all parameters into an array and unpacks them inside the function again:
let a = 1,
b = 2,
c = 3,
d = 4
let myarr = {
a,
b,
c,
d
}
function test(ar) {
var {
a,
b
} = split(ar)
console.log(a) // => 1
console.log(b) // => 2
console.log(ar) // => {c: 3, d: 4}
}
test(myarr)
Using a proxy for destructuring is a clever code pattern that can be used for different purposes. As you get the property names of the left side, you can do a lot of crazy stuff like auto-generating functions names from the object keys.
Top comments (0)