libseed-list named arguments
- From: Jonatan Liljedahl <lijon kymatica com>
- To: Seed - Gnome Javascript <libseed-list gnome org>
- Subject: libseed-list named arguments
- Date: Wed, 16 Jun 2010 13:50:57 +0200
Ever wished JS had named arguments? Here's one way to do it:
Function.prototype.named_call = function(self,namedargs) {
var a = Array.prototype.slice.call(arguments,2);
var names = this.argumentNames();
for (var i=0;i<names.length;i++) {
var x = namedargs[names[i]];
if(x) a[i] = x
}
return this.apply(self,a);
}
Function.prototype.argumentNames = function() {
if(this.__parmNames) return this.__parmNames;
var names =
this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
.replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
.replace(/\s+/g, '').split(',');
return this.__parmNames = (names.length == 1 && !names[0] ? [] :
names);
}
Then you can do stuff like this:
f = function(a,b,c) { ... }
f.named_call(this, {a:42,b:'foo'});
It does add some performance cost of course, any ideas how to speed it up?
PS. I use this in AlgoScript so that f(a=>42,b=>'foo') automatically
turns into a named_call(), but only if there where any named args in the
call.
/Jonatan
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]