4 ms·
Object.prototype.become = function(target) { const newProto = Object.getPrototypeOf(target); Object.setPrototypeOf(this, newProto);
by andai 4y ago
Object.prototype.become = function(target) {
const newProto = Object.getPrototypeOf(target);
Object.setPrototypeOf(this, newProto);
for ( let key of Object.keys(this) ) {
delete this[key];
}
Object.assign(this, target);
}
Here's as close as I could get in JS. This fails Object.is(a,b) though, it just makes object A's data the same as B's.
The two objects will desynchronize, unless all their properties are Objects (eg. Arrays) and no new ones are added.
As far as I know there's no way to update all references to an object to point to a new object. Though you could take the article's advice and add a bunch of indirection with getters and setters, referencing an internal "true" object which could be swapped out trivially.
- cxr 4y agoGetters and setters will also desynchronize for similar reasons (new properties being added/removed). In JS you're better served by proxies or to set things up ahead of time so you're not passing a direct object reference, but a mirror instead. <https://bracha.org/mirrors.pdf https://bracha.org/mirrors.pdf> Once you've got all relevant consumers using a mirror or a proxy and all access is therefore mediated, that's when you can freely perform these kind of swaps. As noted by the commenters, however, this is quite a heavyweight solution. Related: > Inside the engine, a clever trick from Smalltalk called `becomes` is used to swap a newborn Proxy and an existing object that has arbitrarily many live references. Thus an object requiring no behavioral intercession can avoid the overhead of traps until it escapes from a same-origin or same-thread context, and only if it does escape through a barrier will it become a trapping Proxy whose handler accesses the original object after performing access control checks or mutual exclusion. > The local jargon for such object/Proxy swapping is “brain transplants”. <https://brendaneich.com/2010/11/proxy-inception/ https://brendaneich.com/2010/11/proxy-inception/> <https://bugzilla.mozilla.org/show_bug.cgi?id=580128 https://bugzilla.mozilla.org/show_bug.cgi?id=580128>