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 Closure VS Prototype | Sveitech

Javascript Closure VS Prototype

Closure Based

A closure-based object is often referred to as a module. A closure-based object encapsulates it’s members, and have “private” data.

var Module = function() {
    var privateMember = 20;

    function getPrivateMember() {
        return privateMember;
    };

    return {
        getPrivateMember: getPrivateMember
    }
}

By using this approach, we create the an object which does not expose it’s private parts. The downside to this, is excessive memory consumption. Each new instance of our module will create a new instance of the getPrivateMember function, and return a reference to it. Also, all variable access is done through the closure, which means a layer of indirection, to access the variable.

The module approach is good for objects which are created once, or only a few times, depending on the application. The memory use and speed difference is very very small. It’s more a matter of taste than actual optimization concerns.

Prototype Based

The same object as above, but created with the prototype chain, looks like this:

var Module = function() {
    this.member = 20;
}

Module.prototype.getMember() {
    return this.member;
}

Sveistrup Technologies