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.

How JavaScript closures work under the hood

83 pointsby dimonomidover 9 years ago

5 comments

ScottBursonover 9 years ago
I&#x27;ve noticed that a lot of people (though not the author of this article) confuse the terms &quot;lambda expression&quot; and &quot;closure&quot;. Perhaps this confusion is worth taking a moment to address here.<p>A closure, as explained in the article, is a pair of a code pointer and an environment. It is an object &quot;inside the machine&quot; that exists at runtime.<p>A lambda expression is a syntactic entity, a piece of source code: something you can see on the screen.<p>A lambda expression <i>evaluates to</i> a closure, just as an integer literal (a string of digits) evaluates to an integer, or a &#x27;new&#x27; expression evaluates to an instance (object).
评论 #10178403 未加载
inglorover 9 years ago
Can&#x27;t talk about closures without mentioning this excellent piece <a href="http:&#x2F;&#x2F;mrale.ph&#x2F;blog&#x2F;2012&#x2F;09&#x2F;23&#x2F;grokking-v8-closures-for-fun.html" rel="nofollow">http:&#x2F;&#x2F;mrale.ph&#x2F;blog&#x2F;2012&#x2F;09&#x2F;23&#x2F;grokking-v8-closures-for-fun...</a>
评论 #10177530 未加载
habermanover 9 years ago
Lua uses a concept called &quot;upvalues&quot; to refer to variables from enclosing scopes. The main observation here seems to be that you can statically determine a unique index for all local variables in any enclosing scope. I&#x27;m not sure exactly how the details work in cases where there are sibling scopes, but anyway it seems like a useful concept and i am surprised the concept&#x2F;terminology is not more common.
评论 #10178289 未加载
Lx1oG-AWb6h_ZG0over 9 years ago
Every implementation of a closure I&#x27;ve encountered creates a new Capture class which stores references&#x2F;copies of all variables the closure uses. I think they do this even if the closure doesn&#x27;t reference any local variables - only class-level ones. In this case, wouldn&#x27;t it be better to just implement it as a local function of the parent class instead of creating a new class? Or does it not matter because the cost of calling this.foo is negligibly similar to this.parent.foo?
Lioover 9 years ago
AFAICT Closures are still much faster than Function.prototype.bind.<p>(<a href="http:&#x2F;&#x2F;jsperf.com&#x2F;bind-vs-closure-setup&#x2F;44" rel="nofollow">http:&#x2F;&#x2F;jsperf.com&#x2F;bind-vs-closure-setup&#x2F;44</a>)<p>Could anyone who knows more about the implementation details point to an explanation of what&#x27;s going on under the surface?
评论 #10178099 未加载
评论 #10178094 未加载
评论 #10178069 未加载