I wish to create an API that can be called in the following fashion:
var f = foo().bar().barAgain().barTheThird();
but not:
var f2 = foo().bar().barTheThird();
barAgain() can only be called after calling bar(), barTheThird() can only be called after calling barAgain() and so on.
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;
};
The above does not work. foo().bar() is called via the method invocation pattern, therefore the keyword this is bound to the object that within _bar.
I have found one solution:
var _bar = function () {
that.barAgain = _barAgain;
delete that.bar;
return that;
};
But this does not feel particularly clean or elegant.
Has anyone come across this sort of problem before? Any suggestions for a more elegant solution?
Thanks in advance!