closure 、this 、callback

closure和this从红宝书的概念来看。

this

这两个点其实是讲的比较烂的了。都在探讨这个。但我也有必要来探索下嘛,从其他角度分析下嘛。

必须意识到的第一件事是函数内部this的值不是静态的,每次你调用一个函数它总是重新求值,但这一过程发生在函数代码实际执行之前。函数内部的this值实际由函数被调用的父作用域提供,更重要的是,依赖实际函数的语法。在所谓的执行上下文细节中会求this的值。

此文: http://yanhaijing.com/javascript/2014/04/30/javascript-this-keyword/
http://davidshariff.com/blog/javascript-this-keyword/
已经很好的解释了this。 http://yanhaijing.com/javascript/2013/12/28/demystifying-this-in-javascript/
下面这篇更加讲的清楚: http://goddyzhao.tumblr.com/post/11218727474/this
http://dmitrysoshnikov.com/ecmascript/chapter-3-this/
基本将了每一种情况,给出了合理的解释。perfect

closure

https://en.wikipedia.org/wiki/Functional_programming == function arguments
函数式参数(“Funarg”) —— 是指值为函数的参数。 http://goddyzhao.tumblr.com/post/11311499651/closures
http://davidshariff.com/blog/javascript-scope-chain-and-closures/ 可以翻译出来,很详细

概念 原理 实现 作用

透过作用域来看 闭包

When to use Closures?

Closures are a powerful concept given to JavaScript and some of the most common situations to use them are:

Encapsulation

Allows us to hide the implementation details of a context from outside scopes, while exposing a controlled public interface. This is commonly referred to as the module pattern or revealing module pattern.

Callbacks

Perhaps one of the most powerful uses for closures are callbacks. JavaScript, in the browser, typically runs in a single threaded event loop, blocking other events from starting until one event has finished. Callbacks allow us to defer the invocation of a function, typically in response to an event completing, in a non-blocking manner. An example of this is when making an AJAX call to the server, using a callback to handle to response, while still maintaining the bindings in which it was created.

Closures as arguments

We can also pass closures as arguments to a function, which is a powerful functional paradigm for creating more graceful solutions for complex code. Take for example a minimum sort function. By passing closures as parameters, we could define the implementation for different types of data sorting, while still reusing a single function body as a schematic.

When not to use Closures ?

Although closures are powerful, they should be used sparingly due to some performance concerns:

Large scope lengths

Multiple nested functions are a typical sign that you might run into some performance issues. Remember, every time you need to evaluate a variable, the Scope Chain must be traversed to find the identifier, so it goes without saying that the further down the chain the variable is defined, the longer to lookup time.