TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Proxy, a new JavaScript ES6 feature

199 pointsby tirthbodawalaabout 7 years ago

32 comments

philboabout 7 years ago
A use case I had for proxies was a circular array type:<p><a href="https:&#x2F;&#x2F;github.com&#x2F;philbooth&#x2F;hoopy" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;philbooth&#x2F;hoopy</a><p>If the index overflows in either direction, loop back round to the start&#x2F;end of the array. I wanted a circular array to use as a fixed-length buffer for receiving data in a streaming JSON parser I wrote:<p><a href="https:&#x2F;&#x2F;github.com&#x2F;philbooth&#x2F;bfj&#x2F;blob&#x2F;61087c194d5675c75569a2e08617a98609b16ead&#x2F;src&#x2F;match.js#L197-L201" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;philbooth&#x2F;bfj&#x2F;blob&#x2F;61087c194d5675c75569a2...</a>
评论 #17102466 未加载
评论 #17107820 未加载
matsemannabout 7 years ago
I used proxies to make a fun library where you can call arbitrary functions, and it tries to make the function based on the name. For instance<p><pre><code> declaraoids.findWhereNameEqualsX(persons, {x: &quot;Mats&quot;}); </code></pre> It will generate the function on the fly.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;Matsemann&#x2F;Declaraoids" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;Matsemann&#x2F;Declaraoids</a>
评论 #17101042 未加载
评论 #17100192 未加载
评论 #17102029 未加载
sametmaxabout 7 years ago
As a Python guy, where we have __setattr__, __setitem__, etc., I was at first wondering why you would use a proxy for such a thing. Better make it part of the language.<p>But the more I think about it, the more I can see that it&#x27;s handy to have an official proxy interface for this, for the case of an external code needing to wrap your object.<p>Also, I&#x27;ve seen so many reinvented wheels for proxies, and usually bad ones, as it seems an easy problem to solve, but there are plenty of edge cases. Proxies avoid the recursive problem altogether.<p>Besides, __dundermethods__ tend to make the language hard to optimize.<p>Still, it&#x27;s really overkill for simple cases like the ones addressed by Object.defineProperty (or @property for Python), as you create a huge layer of indirection for the entire wrapped object. So if you use such a Proxy, you better have a damn good reason.
评论 #17100078 未加载
评论 #17100666 未加载
SimeVidasabout 7 years ago
I’d rather read an article that <i>doesn’t</i> focus on the API (which I can look up on MDN), but rather on the practical use cases (which are merely a footnote in this article ).
评论 #17103773 未加载
kevincennisabout 7 years ago
Proxies can also be really helpful for unit tests.<p>Obviously you have things like sinon for stubbing out methods, but they do have to modify the original object, which I don’t think anybody <i>loves</i>.<p>But you can also wrap your object in a Proxy with handlers that stub certain methods.<p>You can also use proxies to implement validation and observability on objects. Here’s a very minimal example of a sort of Backbone-esque Model class with proxies: <a href="https:&#x2F;&#x2F;gist.github.com&#x2F;kevincennis&#x2F;25ba31b2e9f9c8b7a34047ba0108aff0" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;kevincennis&#x2F;25ba31b2e9f9c8b7a34047ba...</a>
sfa_aokabout 7 years ago
Salesforce use this in their Lightning Framework. I&#x27;ve not gone beyond the surface of that framework, but I&#x27;ve found its use of proxies adds friction to development. Trying to debug in the browser, anything other than a primitive results in a looking at an empty Proxy object - I believe this is a deliberate choice behind the framework in the name of security. But it makes it much harder to discover what&#x27;s in an object - if you don&#x27;t know the name of a property, good luck getting it.<p>Note that this is either due to how the framework uses Proxy, rather than Proxy itself, or I&#x27;m doing it wrong and should do more reading up on it. It really could be the latter - given my level of experience and knowledge, I thought hard about posting this comment!
评论 #17101686 未加载
评论 #17101925 未加载
fergieabout 7 years ago
This is new to me, and it took me a while to see the point, but having read the Mozilla docs (<a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Reference&#x2F;Global_Objects&#x2F;Proxy" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Refe...</a>) I can see a few use cool examples of validation and input correction. That said- all of these things _seem_ to be fairly trivial to achieve without proxies, so I am wondering- what is the killer use-case that you absolutely positively need js proxies for?
评论 #17100517 未加载
评论 #17101525 未加载
评论 #17101897 未加载
cwpabout 7 years ago
I use this for sql queries:<p><pre><code> const user = await db.connect(sql =&gt; sql.getUserById(43)) </code></pre> The <i>sql</i> value is a proxy that looks for a file called &#x27;getUserById.sql&#x27;, reads sql out of it, sends the query to the database, and returns a promise for the result. With caching and some sugar methods, it&#x27;s a pleasant way to use a database.
sgdesignabout 7 years ago
I was talking about this with a friend and he remarked that this could lead to some pretty opaque code where things behave differently from what you&#x27;d usually expect. While I think this is a cool feature, I think I agree with him that you probably want to think twice before using Proxies.
nathanstittabout 7 years ago
I used object proxy to create a DSL for constructing object factories, inspired by Ruby&#x27;s FactoryBot <a href="https:&#x2F;&#x2F;github.com&#x2F;nathanstitt&#x2F;object-factory-bot" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;nathanstitt&#x2F;object-factory-bot</a><p>It&#x27;s pretty handy for generating data for unit tests, but wouldn&#x27;t recommend it for production code since I&#x27;ve discovered Proxy is fairly slow.
loftyalabout 7 years ago
Anyone using redux, I created this using proxies - <a href="https:&#x2F;&#x2F;github.com&#x2F;alnorris&#x2F;redux-actiontyper" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;alnorris&#x2F;redux-actiontyper</a>
hackerbabzabout 7 years ago
Why is this an ES6 feature? Isn&#x27;t ES6 set and implemented? Wouldn&#x27;t this be part of a future spec (ES2018, ES2019, or whatever)?
评论 #17103818 未加载
评论 #17099966 未加载
评论 #17099925 未加载
评论 #17100934 未加载
syspecabout 7 years ago
The use of `document.write` for this entry instead of the usual console threw me off at first.
评论 #17099369 未加载
评论 #17100531 未加载
评论 #17099391 未加载
techsin101about 7 years ago
This is another feature that goes into bucket &quot;I&#x27;ll never use&quot; along generators
评论 #17099679 未加载
评论 #17099666 未加载
评论 #17099852 未加载
评论 #17100773 未加载
评论 #17099624 未加载
评论 #17102433 未加载
评论 #17100097 未加载
Tooabout 7 years ago
I can see a very valuable use case for being able to intercept method calls and attribute lookups to do input validation, logging, etc. But being able to dynamically decide which attributes exists sounds like a nightmare from a code-analysis perspective.<p>Python has had the __getattr__, __setattr__ and friends and once you start using them to be &quot;creative&quot; all static type checkers break down. They are usually frowned upon.<p>Let&#x27;s hope typescript is able to interpret these Proxy objects and that the community don&#x27;t abuse them for all kinds of strange things.
liberatusabout 7 years ago
Big win for JavaScript DSL composers. Reminds me of method_missing and other sharp knives in ruby.
13yearsabout 7 years ago
I implemented JavaScript Safe Navigation using proxies as an experiment to learn more about proxies.<p>This is similar to the TC39 Optional Chaining Proposal <a href="https:&#x2F;&#x2F;github.com&#x2F;TC39&#x2F;proposal-optional-chaining" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;TC39&#x2F;proposal-optional-chaining</a><p><a href="https:&#x2F;&#x2F;gist.github.com&#x2F;dakaraphi&#x2F;6a87168db66fd8f032d2" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;dakaraphi&#x2F;6a87168db66fd8f032d2</a>
haikugingerabout 7 years ago
This makes sense to me - it feels like an interface somewhere in the space of Python&#x27;s properties (using the @property decorator), its descriptor protocol[0] with which properties are implemented, and its system of magic methods like __getattr__ and __getattribute__.<p>I am a bit intrigued about the way it&#x27;s separated from the &quot;nature&quot; of the underlying Object though - in Python, we&#x27;d have a single canonical interface to the data, bound to the class in which the data was instantiated. Here, in ES6, it seems like the data might be attached to a base Object, and you could use that Object with any number of different proxies to provide polymorphic behavior.<p>Overall, these seem like very different philosophies of object-oriented programming. Which I guess makes sense given how the languages have evolved over time.<p>[0] <a href="https:&#x2F;&#x2F;docs.python.org&#x2F;3&#x2F;howto&#x2F;descriptor.html" rel="nofollow">https:&#x2F;&#x2F;docs.python.org&#x2F;3&#x2F;howto&#x2F;descriptor.html</a>
isuckatcodingabout 7 years ago
<a href="https:&#x2F;&#x2F;caniuse.com&#x2F;#feat=proxy" rel="nofollow">https:&#x2F;&#x2F;caniuse.com&#x2F;#feat=proxy</a><p>Seems to have a decent coverage for most users
评论 #17100604 未加载
jaequeryabout 7 years ago
I&#x27;m not really a fan of these &quot;magic&quot; code creators. I&#x27;d use it only as required and not all out.
coleptabout 7 years ago
Proxy is nice but the scope is very limited if you tend to avoid metaprogramming.<p>One use I&#x27;ve found is for library maintainers - a way to expose a large API without taking a hit for requiring the whole thing. We use it to consume parts of that API without having to require all the dependencies and subdependencies.
_bxg1about 7 years ago
Proxies are awesome. I used them to create observables that automatically publish on any mutation, no matter where in the object tree it happens: <a href="https:&#x2F;&#x2F;www.npmjs.com&#x2F;package&#x2F;mutable-model" rel="nofollow">https:&#x2F;&#x2F;www.npmjs.com&#x2F;package&#x2F;mutable-model</a>
评论 #17101947 未加载
caxco93about 7 years ago
This isn&#x27;t actually a new feature, but at least the thread is giving it some more exposure. It&#x27;s been implemented on many browsers for some time already. I&#x27;ve for example used it for doing quick data-binding. It&#x27;s really useful and more people should know about it.
Boulthabout 7 years ago
Proxies are hardly new (2014?), well, just like Es6. There are some interesting applications [0] but I don&#x27;t know if is use it in production.<p>[0]: <a href="https:&#x2F;&#x2F;curiosity-driven.org&#x2F;array-slices" rel="nofollow">https:&#x2F;&#x2F;curiosity-driven.org&#x2F;array-slices</a>
icc97about 7 years ago
&gt; Data persistence. We add a proxy backup function to each object that is fired when modifying its content.<p>This makes me think of database triggers, which would imply that it&#x27;s quite easy to implement dark patterns with Proxies.
ramadisabout 7 years ago
I made a simple library to add ruby&#x27;s `method_missing` to Javascript: <a href="https:&#x2F;&#x2F;github.com&#x2F;ramadis&#x2F;unmiss" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;ramadis&#x2F;unmiss</a>
rutierutabout 7 years ago
Was looking for something exactly like this the other day! No idea this existed, this will especially be great while stubbing&#x2F;mocking in tests.
foobabout 7 years ago
Proxies are definitely fun. We use them extensively in our browser automation framework, which is largely based on the Web Extensions API [1], to implement syntactic sugar in the interface. The general goal behind Remote Browser [2] is to make it really easy to execute privileged code in a web browser, but to otherwise stay out of your way as much as possible. This is accomplished through the heavy use—some might even say <i>abuse</i>—of proxies.<p>For instance, take a look at this code example of opening a tab.<p><pre><code> await browser.evaluateInBackground(createProperties =&gt; ( browser.tabs.create(createProperties) ), { url: &#x27;https:&#x2F;&#x2F;intoli.com&#x27; }); </code></pre> The <i>browser.evaluateInBackground()</i> method is part of the Remote Browser API, and it simply evaluates code in a background script context in the browser. The <i>browser.tabs.create()</i> call, on the other hand, is part of the Web Extensions API. The vast majority of Remote Browser&#x27;s power is provided through remote code execution and the Web Extensions API, so we really wanted to provide a more concise syntax for performing this sort of operation. Using proxies, we were able to make the <i>browser</i> object directly callable as a shorthand for background context evaluation. This code example is exactly equivalent to the previous one.<p><pre><code> await browser(createProperties =&gt; ( browser.tabs.create(createProperties) ), { url: &#x27;https:&#x2F;&#x2F;intoli.com&#x27; }); </code></pre> That&#x27;s a bit more concise, but the real sugar is in the next step of abstraction. Instead of explicitly evaluating a function in the background script context, you can simply treat the <i>browser</i> object in the client context as though it were the Web Extensions API <i>browser</i> object in the background script context. This code example is again exactly equivalent, and again accomplished using proxies.<p><pre><code> await browser.tabs.create({ url: &#x27;https:&#x2F;&#x2F;intoli.com&#x27; }); </code></pre> The <i>tabs.create</i> method isn&#x27;t hardcoded into the Remote Browser library. Instead, proxies are used to evaluate any non-local API calls in the background script context. This means that you automatically get full access to the version of the Web Extensions API that your browser supports, whether you&#x27;re using Chrome, Edge, Firefox, or Opera.<p>The one last piece of syntactic sugar is the shorthand for evaluating code inside of individual tabs. The syntax is very similar to how you evaluate functions in the background script context, you just need to first use square brackets to indicate the tab ID.<p><pre><code> await browser[tab.id](createProperties =&gt; ( document.getElementById(&#x27;some-link&#x27;).innerHTML ), { url: &#x27;https:&#x2F;&#x2F;intoli.com&#x27; }); </code></pre> This is <i>also</i> implemented using proxies. In fact, the same trap that handles the local Web Extensions API calls handles the tab access, and it differentiates between the two depending on whether or not the property name consists entirely of integers. In both cases, it returns <i>another</i> proxy that is able to handle either additional chaining or function evaluation.<p>Anyway, sorry that this ended up a lot more long-winded than I was expecting. If this has piqued your interest in Remote Browser though, we made an interactive tour of the project that you should check out [3]. You can actually launch and control browsers from inside of your own browser in the tour, and it explains a lot more about the project philosophy and what you can do with it<p>[1] - <a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;Add-ons&#x2F;WebExtensions&#x2F;API" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;Add-ons&#x2F;WebExtensions&#x2F;AP...</a><p>[2] - <a href="http:&#x2F;&#x2F;github.com&#x2F;intoli&#x2F;remote-browser&#x2F;" rel="nofollow">http:&#x2F;&#x2F;github.com&#x2F;intoli&#x2F;remote-browser&#x2F;</a><p>[3] - <a href="https:&#x2F;&#x2F;intoli.com&#x2F;tour" rel="nofollow">https:&#x2F;&#x2F;intoli.com&#x2F;tour</a>
hguhghuffabout 7 years ago
I liked the functionality but found it hard to implement. Not a good sign.<p>Successful features are those that surprise in the easy direction (arrrow functions) rather than in the hard direction (proxies).
评论 #17099978 未加载
rijojaabout 7 years ago
So this is sort of like metatables in lua?
评论 #17099757 未加载
评论 #17099645 未加载
celim307about 7 years ago
Does es6 tags use this under the hood?
hungerstrikeabout 7 years ago
Unfortunately IE doesn&#x27;t Proxies them at all and you can&#x27;t even shim support for them on IE.