An illustration of "private" variables : 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 "new
 * Sequence(), 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 = function () {
    var data = [];
    
    this.append = function (item) {
        data.push(item);
    };
        
    this.itemAt = function (position) {
        return data[position];
    };
};

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