定义
A closure is the combination of a function and the lexical environment within which that function was declared.
1 | function makeAdder(x) { |
Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data.
Use case
makeSizer
1 | body { |
1 | function makeSizer(size) { |
Emulating private methods with closures
Using closures in this way is known as the module pattern:
1 | var counter = (function() { |
Using closures in this way provides a number of benefits that are normally associated with object-oriented programming – in particular, data hiding and encapsulation.
1 | var makeCounter = function() { |
Performance considerations
It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.
1 | function MyObject(name, message) { |
Because the previous code does not take advantage of the benefits of using closures in this particular instance, we could instead rewrite it to avoid using closure as follows:
1 | function MyObject(name, message) { |
However, redefining the prototype is not recommended. The following example instead appends to the existing prototype:
1 | function MyObject(name, message) { |