I currently have the following javascript code (loosely modeled after how a similar objective is achieved in should.js):
var example = function() {
var isFoo, isBar;
return {
baz: function(x) {
if (isFoo) return x + 2;
else if (isBar) return x - 2;
},
get foo () {
isFoo = true;
return this;
},
get bar () {
isBar = true;
return this;
},
}
};
This allows me to do something like:
example().foo.baz(2);
// 4
My primary objective is to allow foo and bar to be called without requiring parenthesis since they will never take any arguments themselves and makes chaining together calls a lot more readable. When I passed this code through uglify.js it choked on the get keyword and when I investigated I found that using the get keyword isn’t really a great idea (both for performance and compatibility).
Any thoughts on how I could refactor this piece of code so that I can continue to call foo and bar without parenthesis and without resorting to using the get keyword? I’ve tried defining foo and bar as properties but couldn’t figure out how to make it work.
You could use
__defineGetter__, but that’s not a terribly great idea either. Firefox has some new metaprogramming apis, but this is unusable in any other browser.The baseline is that if you want your code to run in old browsers, this can’t be done.