TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: What is the difference between a closure and an object?

2 点作者 irixusr大约 9 年前
Reading PG&#x27;s criticism about OOP, he mentions that if he ever really needed objects, he&#x27;d use an array of closures instead. When I read this I knew little about what closures were, so intrigued I read up I them.<p>Now I can&#x27;t figure out how they&#x27;re different, except how a language might implement them.<p>So what is the conceptual and practical difference between the two?

4 条评论

sova大约 9 年前
An object has state, so imagine you have a skeleton and every time you change a property you are taking off an old bone and putting on a new bone. Eventually you might have 3 femurs, a couple of skulls, and five knees because of how objects are implemented (and how hard it is to keep straight).<p>A closure is like if you needed a forearm, you created one on-the-fly for the specific instance, and it exists as long as it&#x27;s needed. You would never have the issue of having excess multiples of arms or legs because closures, although maintaining an internal state, only exist as long as they are invoked.<p>It&#x27;s a simple example, but maybe that helps clear it up. Perhaps some people can help extend the metaphor if it proves useful.
al2o3cr大约 9 年前
@irixusr I&#x27;d recommend this page from C2:<p><a href="http:&#x2F;&#x2F;c2.com&#x2F;cgi&#x2F;wiki?ClosuresAndObjectsAreEquivalent" rel="nofollow">http:&#x2F;&#x2F;c2.com&#x2F;cgi&#x2F;wiki?ClosuresAndObjectsAreEquivalent</a><p>It may also help to contemplate the techniques used to get &quot;private variables&quot; in vanilla Javascript.
stonemetal大约 9 年前
In theory they are the same thing, in practice they are not.<p>If you treat closures like objects, they are tedious, and missing lots of nice conveniences that OO languages provide for their objects.<p>If you treat Objects like closures then they are heavy weight, have too much formality, and have annoying limitations to work around.
ScottBurson大约 9 年前
The fundamental difference is this: a closure has a single operation; when you invoke it, it does that one thing. An object, in contrast, normally has many operations, so to invoke one of them, you have to supply its name.<p>That&#x27;s not a big difference, but it is a difference.