Chapter 2 - closures

by Denise Nepraunig

HTML

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

JavaScript

// Programming JavaScript Applications
// Chapter 2
// closures

// the o is a factory object !!
var o = function o () {
    var data = 1,
        get;
    
    get = function get() {
        return data;
    };
    
    return {
        get: get
    };
};

QUnit.test("closure test", function (assert) {
    var obj = o();
    // dafuq - don't forget the () - otherwise we don't get the object!
    try {
        assert.ok(data, "This throws an error"); // this test never runs
    } catch (e) {
        assert.ok(true, "The data variable is only available" +
                  "to priviledged methods");
    }

    assert.equal(obj.get(), 1, "get is a priviledged method and gets "  +
                 "the data");
});