Difference between revisions of "Closure"

From Organic Design wiki
m (Example)
m (typo)
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{glossary}}
+
#redirect [[JavaScript#Closures]]
A closure is like a bubble in [[JavaScript]] in that it acts like a separate self-contained global scope, and can contain variables, functions, and even entire JavaScript frameworks like [[jQuery]]. Closures can have both a private and public aspect, they're in the form of a function rather than an object, and are brought into existence by calling it, what's returned is the public interface. The content of the scope within the closures definition is private and exists for as long as the returned public interface exists.
 
 
 
The [[viewer]] onto the [[unified ontology]] intenernally maintains a closure for each [[node]], and many of these nodes have a visible interface aspect in the form of an associated DOM element in the page. The unified ontology viewer also allows each node to be persistent by storing them in a [[peer-to-peer]] semantic network.
 
 
 
== Example ==
 
The following example illustrates a simple closure example. The variable ''foo'' is private and can only be accessed by functions in the same private scope, or by the functions returned in the public interface. An instance of the closure is created in the variable ''closure'' by being assigned the value returned by anonymously executing the declared function.
 
{{code|<js>var closure = ( function() {
 
    var foo = 1;
 
    return {
 
        bar: 100,
 
        baz: function() {
 
            alert( foo );
 
            alert( this.bar );
 
        }
 
    }
 
} )();
 
alert( closure.bar );
 
closure.baz();</js>}}
 
 
 
 
 
In this example, the public function ''baz'' can access the private ''foo'' variable from it's local scope. The public interface also includes a variable ''bar'' which can be accessed publicly or via ''this'' from within the executing public interface functions. All of the items in both the private and the public scopes of the closure exist for the lifetime of the ''closure'' object.
 
 
 
== See also ==
 
*[http://jibbering.com/faq/notes/closures/ Understanding closures]
 
*[[The Module pattern]]
 
*[[JavaScript]]
 
*[[jQuery]]
 

Latest revision as of 21:14, 10 November 2015