arguments
are a very specific thing, about which novices and even amateurs know only that this is “like an array, but some kind of wrong”. In fact, it has a number of interesting features. I suggest in the topic to fantasize on TypeHinting, the default arguments and any other. (function (foo, bar) { console.log(typeof arguments); // ? arguments[0] = 42; console.log(foo); // ? })(10, 20);
function test (foo, bar) { Args(arguments).defaults(100, 100); return [foo, bar]; }; test( ); // 100, 100 test(15 ); // 15, 100 test(21, 42); // 21, 42
var object = {}
(function () { console.log( typeof arguments, // object Object.getPrototypeOf(arguments) == Object.prototype // true ) })();
var array = Array.prototype.slice.call(arguments, 0); // , : var array = [].slice.call(arguments, 0);
slice
method of the Array prototype on behalf of arguments
.arguments.length
arguments.length
- the number of arguments passed to the function. var count = function () { console.log(arguments.length); }; count(); // 0 count(first, second); // 2
length
property, which indicates how many elements are declared in its header: function one (foo) {}; function three (foo, bar, qux) {}; console.log( one.length); // 1 console.log(three.length); // 3
arguments.callee
arguments.callee
- reference to the function itself. function foo () { console.log(arguments.callee === foo); // true }
function test (foo, bar, qux) { return arguments.callee.length === arguments.length; } test(1); // false test(1,2,3); // true
arguments
also contains a list of arguments passed. function test (foo, bar) { console.log(foo, bar); // 'a', 'b' console.log(arguments[0], arguments[1]); // 'a', 'b' } test('a', 'b');
(function (foo) { arguments[0] = 42; console.log(foo); // 42! foo = 20; console.log(arguments[0]); // 20 })(5);
function foo (qux) { change(arguments); return qux; }; function change(a) { a[0] = 42; } foo(10); // 42
function ($foo = 30, $bar = 'test') { var_dump($foo); var_dump($bar); }
function (foo, bar) { if (typeof foo === 'undefined') foo = 30; if (typeof bar === 'undefined') bar = 'test'; console.log(foo, bar); }
arguments
you can create a beautiful interface: function test(foo, bar) { Args(arguments).defaults(30, 'test'); console.log(foo, bar) } test(); // 30, 'test'
function Args (args) { if (this instanceof Args) { this.args = args; } else { // new, , return new Args(args); } }; Args.prototype = { defaults: function () { var defaults = arguments; for (var i = defaults.length; i--;) { if (typeof args[i] === 'undefined') args[i] = defaults[i]; } return this; } };
function test(foo) { Args(arguments) .defaults(10) .cast(Number); console.log(foo) } test('0100'); // 100
function test(foo, bar) { Args(arguments).types(Foo, Bar); // code } test(new Foo(), new Bar()); test(1, 2); // Error
function test (foo, bar, qux) { Args(arguments).allRequired(); } test(1,2,3); // success test(1,2); // Error: 3 args required, 2 given
Source: https://habr.com/ru/post/117868/
All Articles