JavaScript: force the order in which function properties of a module can be called
<p>I wish to create an API that can be called in the following fashion:</p>

<pre><code>var f = foo().bar().barAgain().barTheThird();
</code></pre>

<p>but not:</p>

<pre><code>var f2 = foo().bar().barTheThird();
</code></pre>

<p><em>barAgain()</em> can only be called after calling <em>bar()</em>, <em>barTheThird()</em> can only be called after calling <em>barAgain()</em> and so on.</p>

<pre><code>function foo() {
    var that = {};

    var _bar = function () {
        return that;
    };

    var _barAgain = function () {
        return that;
    };

    var _barTheThird = function () {
        return that;
    };

    _barAgain.barTheThird = _barTheThird;
    _bar.barAgain = _barAgain;

    that.bar = _bar;

    return that;
};
</code></pre>

<p>The above does not work. <em>foo().bar()</em> is called via the method invocation pattern, therefore the keyword <em>this</em> is bound to the object <em>that</em> within _<em>bar</em>.</p>

<p>I have found one solution:</p>

<pre><code>var _bar = function () {
    that.barAgain = _barAgain;
    delete that.bar;
    return that;
};
</code></pre>

<p>But this does not feel particularly clean or elegant.</p>

<p>Has anyone come across this sort of problem before?  Any suggestions for a more elegant solution?</p>

<p>Thanks in advance!</p>
