user123123123 user123123123 - 5 months ago 9
Javascript Question

Access parameters like a bash script

I want to access my routine parameters like in a bash script, by using the dollar prefix and the parameter number ($1 = first parameter, $2 = second parameter), my function signature must be empty.

function foo (/* Empty */) {
return $1 + $2 + $3;
}

foo(2, 2, 4); // => 8


How can i do this? I tried using the apply method without success.

foo.apply(null, { $1: 2, $2: 2, $3: 4 });

Answer

Please do not use this in production code:

Object.defineProperties(window, {
  '$1': { get: function fn() { return fn.caller.arguments[0]; } },
  '$2': { get: function fn() { return fn.caller.arguments[1]; } },
  '$3': { get: function fn() { return fn.caller.arguments[2]; } },
  '$4': { get: function fn() { return fn.caller.arguments[3]; } },
  '$5': { get: function fn() { return fn.caller.arguments[4]; } }
});

var a = function() {
  console.log($1, $2, $3, $4, $5);
};

a("Hello", "I can't beleave", "this", "actually", "works!");

Wont work with "use strict" though.