izuzak.github.com
izuzak.github.com copied to clipboard
(post comments) Named arguments in JavaScript
This issue is reserved for comments on the blog post Named arguments in JavaScript. Leave a comment below and it will show up on the blog post's Web page. Thanks!
I thought about doing something very similar but to use a decorator on the functions instead of the invocations (naturally there should be less of the former than the latter) The flow will look something like:
funcA = namedArgs(function (argA, argB) {
return [argA, argB];
});
funcA(1,2); // return [1,2];
funcA(KW("argB", 3), KW("argA", 4)); // return [4,3]
funcA(KW( {argB:3, argA:4} )); // return [4,3]
where: KW returns a "marked" (special property, or something) dict object from a dict or argument pairs namedArgs returns a function that does pretty much what you've done in "callWithNamedArgs" - something along the lines of:
function namedArgs(wrapped) {
var argsNames = getNamesFromFunc(wrapped)
return function() {
var extractedKWs = extractKWs(arguments) // dict
var extractedPositionals = extractPositionals(arguments) // array
var argList = []
for (argName in argNames) {
if (argName in extractedKWs) {
argList.append(extractedKWs.pop(argName)); // assuming python-like pop for dict
} else {
argList.append(extractedPositionals.pop());
}
}
argList.append(extractedPositionals); // allow function to access the rest of the undeclared positionals
argList.append(extractedKWs); // same for undeclared named args
return wrapped.apply(this, argList);
};
}
As you can see, it also has the benefit of having access to the undeclared but passed positional and named args. What do you think?
hey m0she, thanks for your comment
in short - i like your version also. i think that the difference in the wrapping of the underlying function is a matter of style more than of functionality. however, i do think that having the ability to pass in other positional args is a cool feature to have. nice!
and i always forget... are named arguments on the roadmap for ecmascript 5 (harmony) ?
Yesterday I wrote an article about creating functions that accept named variables: http://cwestblog.com/2013/06/17/javascript-passing-arguments-by-name/. Basically I added Function#index to the prototype. Of course, as many people prefer not to extend the prototype of native objects you can simply modify the function so that it isn't prototypal but here is an example of using Function#index:
var showA2D = (function(a, b, c, d) {
console.log('a = ', a);
console.log('b = ', b);
console.log('c = ', c);
console.log('d = ', d);
}).index();
showA2D({
a: "first parameter",
d: "last parameter",
b: "second parameter"
});
The following would result from using the above code:
a = first parameter
b = second parameter
c = undefined
d = last parameter