Chapter 2 - IIFE

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
// IIFE - Immediatlely Invoked Function Expression

// used to create new scope (keep the global scope clean) to encapsulate modules

// Before IIFE - BEGIN

var Lightbulb = function () {
    this.isOn = false;
};
var lightbulb = new Lightbulb();

Lightbulb.prototype.toggle = function() {
    this.isOn = !this.isOn;
    return this.isOn;
};

// Before IIFE - END

QUnit.test("lightbulb test", function (assert) {
    assert.equal(lightbulb.toggle(), true, "toggle turns the new lightbulb on");
    assert.equal(lightbulb.toggle(), false, "another toggle turns the new lightbulb off");
});

// After IIFE - BEGIN

(function () {
    var isOn = false,
        toggle = function toggle() {
            isOn = !isOn;
            return isOn;
        },
        lightbulb = {
            toggle: toggle
        }; // here the VAR statement ends
    
    QUnit.test("lightbulb IIFE", function (assert) {
        assert.equal(lightbulb.toggle(), true, "toggle turns the lightbulb on");
        assert.equal(lightbulb.toggle(), false, "toggle turns the lightbulb off");
    });
}());