Do you still use argument to give information for other components? It's the most simple way, but sometimes it's too long to read. We can use other approach like named parameter, chain and deferred.
Named parameter
function foo(param) { alert(param && param.bar || ''); } foo({ bar: 'hello, world' });
Chain
function foo(f) { return { bar: function(b){ alert(f + b); } }; } foo('hello, ').bar('world');
$.Deferred
function openTargetChooser(){ var deferred = $.Deferred(); $('#btn-accept').click(function(){ deferred.resolve($('#target').val()); }); $('#btn-close').click(function(){ deferred.reject(); }); $('#dialog').show(); return deferred.promise(); } openTargetChooser().done(function(param){ alert('complete!' + param); }).fail(function(){ alert('wow!'); });
CoffeeScript
To improve interface, we have to pay much attention for inner implementation. But CoffeeScript helps you to minimize your cost because:
- .? operator is useful to avoid 'undefined' problem
- default values for argument is useful to provide simple API
- writing anonymous function is easy
So we can shorten our code like:
foo = (param) -> alert param?.bar || '' foo bar:'hello, world'
foo = (head) -> return bar: (tail) -> alert(head + tail) foo('hello, ').bar('world')