Path: csiph.com!weretis.net!feeder8.news.weretis.net!news.mb-net.net!open-news-network.org!.POSTED.178.197.205.59!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: [Proxy] No way to hook property creation? Date: Mon, 22 Aug 2022 01:08:06 +0200 Organization: PointedEars Software (PES) Lines: 74 Message-ID: <2658833.mvXUDI8C0e@PointedEars.de> References: Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit Injection-Info: gwaiyur.mb-net.net; posting-host="178.197.205.59"; logging-data="1505928"; mail-complaints-to="abuse@open-news-network.org" User-Agent: KNode/4.14.10 Cancel-Lock: sha1:AF9rpRAgqZU1f8+WmLipifDI0l4= X-User-ID: U2FsdGVkX1/SB3YLxXfCQz01pG9OrD3LJdqKmh6QlMmiCmRJkBD/Xg== X-Face: %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&. I'm trying to use Proxy and the `with` statement to redirect access to the > global object. > > The problem is that, Proxy doesn't seem to have any handler for property > creation which is done without object accessor or > `Object.defineProperty()`. e.g. `prop = 123` instead of `obj.prop = 123` The (by-design) inconsistent and unpredictable behavior of the *legacy* “with” statement that *never* a property on the target object is being created with implicit access, but either a) the property of an object higher up in the scope chain is modified – or not if it is read-only or has a dismissive object value getter (host object) or property setter, or b) a property of the global object is created (or not) is one of the reasons why it is *deprecated* since ECMAScript Edition 5, and *code containing it cannot even be executed* in Strict Mode. This has nothing to do with the capabilities of the Proxy object because its instance does not even "see" that write access. You can determine whether a property is being created in the “set” handler of the Proxy instance: var target = {}; var proxy = new Proxy(target, { set (target, propertyName, value) { var propertyExisted = (propertyName in target); target[propertyName] = value; if (!propertyExisted) { console.log(`Created property "${propertyName}" on target with value "${value}".`); } } }); /* * displays * "Created property "foo" on target with value ""bar"" */ proxy.foo = "bar"; /* does not display anything */ proxy.foo = "baz"; Tested in Chromium 90 on GNU/Linux, navigator.userAgent == "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36". The usual caveats for the “in” statement and ES 6+ features apply. See also: -- PointedEars | Twitter: @PointedEars2 Please do not cc me. /Bitte keine Kopien per E-Mail.