CSC/ECE 517 Fall 2011/ch1 1c cm: Difference between revisions
Line 19: | Line 19: | ||
An example of creating a closure in JavaScript. Note that the scope of the parameter <code>n</code> is limited to the inside of the <code>add</code> function. However, because <code>add</code> returns a closure, that closure has access to <code>n</code> when it is evoked. | An example of creating a closure in JavaScript. Note that the scope of the parameter <code>n</code> is limited to the inside of the <code>add</code> function. However, because <code>add</code> returns a closure, that closure has access to <code>n</code> when it is evoked. | ||
<pre> | <code><pre> | ||
function add(n) { | function add(n) { | ||
return function (x) { | return function (x) { | ||
Line 31: | Line 31: | ||
alert(add5(6)); // 11 | alert(add5(6)); // 11 | ||
alert(add10(6)); // 16 | alert(add10(6)); // 16 | ||
</pre> | </pre></code> | ||
=== First-class functions === | === First-class functions === |
Revision as of 19:46, 3 September 2011
Introduction
high-level overview, who we are trying to target
Closures vs. Methods
introduction of the battle of functional versus object oriented history of the closures with scheme and future languages history of OO methods with C++ and other languages
Summary Table
graphical breakdown of the two and the features we think are important for each
Closures
A closure is a block of executable code together with a reference to the local variables in the environment in which it was created. Those local variables are captured by the closure, and their lifetime is extended to be at least as long as the lifetime of the closure. Closures can be created by defining a function within the body of another function. Anonymous functions are usually implemented as closures.
An example of creating a closure in JavaScript. Note that the scope of the parameter n
is limited to the inside of the add
function. However, because add
returns a closure, that closure has access to n
when it is evoked.
function add(n) {
return function (x) {
return x + n;
};
}
var add5 = add(5);
var add10 = add(10);
alert(add5(6)); // 11
alert(add10(6)); // 16
First-class functions
closures are typically first-class functions (define first-class functions)
Execution-time environment contains free variables
closures capture variables referenced at the time they are created and the lifetime of those captured variables is extended to at least as long as the lifetime of the closure
Methods
methods and classes are associated with object-oriented programming
Instance or static class functions
methods are functions associated with an object
Execution-time environment contains instance or static variables
methods operate on state associated with an object (environment is closed, but defined by the programmer at compile time)