kwargs

See https://github.com/serkanyersen/kwargsjs

by Andy Bulka

HTML

Playing with kwargs
<hr>
<div class="log">
    <a href="#" id="clearlog">Clear</a>
    <div id="log"></div>
</div>
<hr>

JavaScript

function msg(s) {
    $('<div/>').append(s).appendTo('#log');
}
$('#clearlog').click(function() {
    $("#log").empty();
});

// -----------------------------

// Copyright (c) Serkan Yersen

(function(){
    'use strict';

    Function.prototype.kwargs = function (defaults) {

        var func = this;
        var removeComments = new RegExp('(\\/\\*[\\w\\\'\\s\\r\\n\\*]*\\*\\/)|(\\/\\/[\\w\\s\\\'][^\\n\\r]*$)|(<![\\-\\-\\s\\w\\>\\/]*>)', 'gim');
        var removeWhitespc = new RegExp('\\s+', 'gim');
        var matchSignature = new RegExp('function.*?\\((.*?)\\)', 'i');
        // get the argument names from function source
        var names = func.toString()
                        .replace(removeComments, '')
                        .replace(removeWhitespc, '')
                        .match(matchSignature)[1]
                        .split(',');

        // Check the existance of default, if not create an object
        if(defaults !== Object(defaults)){
            defaults = {};
        }

        return function() {
            var args = Array.prototype.slice.call(arguments),
                kwargs = args[args.length - 1],
                name;

            // Check the existance of the kwargs
            if (kwargs === Object(kwargs)) {
                args.pop();
            }else{
                kwargs = {};
            }

            // Fill the arguments and apply them
            for (var i = 0; i < names.length; i++) {
                name = names[i];
                if (name in kwargs) {
                    args[i] = kwargs[name];
                }else if(name in defaults && args[i] === undefined){
                    args[i] = defaults[name];
                }
            }

            return func.apply(this, args);
        };
    };
})();

// ------------------------------------------

var test = function(arg1, arg2, arg3){
    // Your code
    msg('arg1='+arg1+' arg2='+arg2+' arg3='+arg3);
}.kwargs();

$(function () {
    // Interesting use...