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

科技回声

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

GitHubTwitter

首页

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

资源链接

HackerNews API原版 HackerNewsNext.js

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

Closures explained with JavaScript

4 点作者 skilldrick大约 14 年前

1 comment

happy4crazy大约 14 年前
Nice article :)<p>The thing that helped me understand closures was really thinking about <i>why</i> they're confusing for beginners.<p>For example, let's say you show the following code to someone who's never heard of closures, and ask them what it should do.<p><pre><code> var foo = 0; var f = function() { return foo; } f(); </code></pre> The thing that's confusing to beginners here is that <i>there is no right answer</i> to this question, and yet by being asked the question, you feel like you should be able to intuit the "right" behavior. For example, the previous code returns 0, but the analogous code will break in Ruby:<p><pre><code> foo = 0 def f foo end f # =&#62; NameError: undefined local variable or method `foo' ... </code></pre> And then you say, er, Ruby does closures too:<p><pre><code> foo = 0 define_singleton_method :f do foo end f # =&#62; 0 </code></pre> How to handle this situation is up to the programming language: it might break, or it might use dynamic scope, or it might use closures/lexical scope (any others?).<p>Closures are initially confusing not because they're a difficult topic, but because their entire existence hinges on a programming language design decision that you, as a beginner, know nothing about. You can't see it in the text of the program. I think that if you clarify up front that someone, back in the day, realized that it would be pretty cool if languages worked liked <i>this</i>, instead of like <i>that</i>, then it makes understanding closures a lot easier.
评论 #2474599 未加载