Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Last active October 19, 2021 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crutchcorn/3ea5a71b29d7b2074868837c21ef4272 to your computer and use it in GitHub Desktop.
Save crutchcorn/3ea5a71b29d7b2074868837c21ef4272 to your computer and use it in GitHub Desktop.
Demonstration of how Object.assign, object mutation, and proxy binding play together in JS
const a = {
a: 100
}
const c = {
c: 300
}
function get_c_proxy(mainObj) {
return new Proxy(c, {
get: function (object, name) {
return object[name] + mainObj.b;
}
})
}
/**
* Because we're passing "a" to Object.assign,
* `b` will be mutated onto the
* existing variable memory address
*
* Then, later, when we pass that object to `get_c_proxy`, it
* will be able to access that vairable
*/
Object.assign(a, {
b: 200
}, get_c_proxy(a));
console.log(c.c); // Logs "300". Reading original object
console.log(a.c); // Logs "500". Reading from newly assigned data
// Keep in mind that `Object.assign` only works by iterating through props and assigning the values.
// This means they're no longer trapped via the proxy and won't update future proxied object values
c.c = 0;
console.log(c.c); // 0
console.log(a.c); // 500. Was not updated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment