Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 81 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 82 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 81 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 82 Javascript Closures | Sveitech

Javascript Closures

A Basic Closure

Every function in javascript creates a closure. A closure is a collection of variables existing in the scope of the function. When a function is created, it creates a repository called a VariableEnvironment. The VariableEnvironment contains all variables which is exist in the current scope. Additionally, a function creates a property called [[scope]], which points to the parent function’s VariableEnvironment. So just like the protototype property, the [[scope]] property creates a hierarchy of VariableEnvironments.

What this means is, that every function existing withing another function, automatically inherits all properties of the outer function, and can use them later on. Because the inner function refers to outer properties, they will not go out of scope, when the outer function exits, because the inner function still points to them. This means that they will not be garbage collected, as long as some function somewhere still has a reference to that VariableEnvironment.

Below is seen a basic example:

var object = function() {
	var local_1 = 10;
	var local_2 = 20;

        // VariableEnvironment: {local_1: 10, local_2: 20, [[scope]]: null}

	return function(value) {
                // VariableEnvironment: {[[scope]]: {local_1: 10, local_2: 20, [[scope]]: null}}
		return value + local_1 + local_2;
	};
};

Pitfalls

Closures create property references, not copies. This can cause some tricky bugs. Consider the example:

var func = function() {
    var local = 10;

    var gizmo = function () {
        return local * 10;
    }

    local = 20;

    return gizmo;
}

func();

In the example above, calling func() will return 20, because the gizmo function has a reference to the local property, whose last value was 20.

Sveistrup Technologies