A lot of properties in my objects may be either a value or a function that returns a value. Accessing a value is different to calling a function (foo; vs foo();). I currently take the following approach. Can anyone recommend anything better?
var foo = {
bar: function(){
return 1;
},
// bar: 1, // bar may also be a standard value
GetBar: function(){
return $.isFunction(this.bar) ? this.bar() : this.bar;
},
Get: function(property){
return $.isFunction(property) ? property() : property;
}
}
foo.GetBar();//1
foo.Get(foo.bar);//1
I’m currently using the foo.GetBar(); approach, but because I then have to write a a new function for every property than van be either a value or a function, I am thinking that it is best to go with the foo.Get(foo.bar); approach to keep it DRY. If you cannot recommend a better solution, I would still like to hear your feedback on both of the supplied methods.
Thanks.
I generally use a global utility in this case to turn every property that might be a function into one, then always call the function instead of accessing the property:
It looks a little silly in that example, but it’s easy enough to incorporate it into an object like yours:
I usually use this approach for configuration variables that might be values or functions – in that case I call
functoron the way in rather than the way out: