An illustration of "private" variables : non-constructor version

A small example of a data type with a "property" that can only be accessed via methods.

by Ray Toal

HTML

<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>

JavaScript

/*
 * A simple sequence data type, illustrating "private" storage.
 * The advantage is that once a sequence is created via the
 * invocation Sequence.create(), the field "data" is inaccessble 
 * directly; it can only be accessed via append and itemAt.  
 * The disadvantage is that every sequence created has its own 
 * copy of the append and itemAt methods.
 */

var Sequence = {
    create: function () {
        var data = []; 
        
        return {
            append: function (item) {
                data.push(item);
            },
        
            itemAt: function (position) {
                return data[position];
            }
        };
    }
};

test("Sequence test", function () {
    var s1 = Sequence.create();
    var s2 = Sequence.create();
    s1.append(0);
    s1.append(1);
    s2.append("2");
    equal(s1.itemAt(0), 0);
    equal(s1.itemAt(1), 1);
    equal(s2.itemAt(0), "2");
});