Chapter 8 - Functions

8.4.1 & 8.6

by Denise Nepraunig

JavaScript

// JavaScript The Definitive Guide 6th Edition
// 8.4.1 Function properites & 8.6 Closures

// 8.4.1 functions can have properties, since they are special objects
uniqueInt.counter = 0;

function uniqueInt() {
    return ++uniqueInt.counter;
}

console.log(uniqueInt());
console.log(uniqueInt());

// but the function property is visible to everyone
// so this is a really bad idea

// but you know what? let's use closures instead

var uniqueInteger = (function () {
    var counter = 0; // the counter acts like a private variable
    return function () {
        return ++counter;
    };
}());

console.log(uniqueInteger());
console.log(uniqueInteger());
console.log(uniqueInteger);

function counter() {
    var n = 0;
    return {
        count: function () {
            return ++n;
        },
        reset: function () {
            n = 0
        }
    };
}
// so each function has its own private 'closure/scope'
// however this is called
var c = counter(),
    d = counter();
c.count();
d.count();
c.reset();
c.count();
d.count();
c.reset();

console.log(c.count());
console.log(d.count());

function count(n) {
    return {
        get count() {
            return ++n;
        },
        set count(m) {
            if (m >= n) n = m;
            else throw Error("count can only be set to a larger value");
        }
    };
}

var a = count(1000);
a.count;
a.count;
console.log(a.count);

a.count = 2000;
a.count;
a.count;
console.log(a.count);

try {
    a.count = 100;
} catch (e) {
    console.log(e.message);
}