Named Arguments

Lecture




Named arguments are not related to arguments .

This is an alternative technique of working with arguments, which allows you to contact them by name, not by number. Often it is much more convenient.

Imagine that you have a function with several arguments, most of which have default values.

For example:

1 function showWarning(width, height, title, contents, showYesNo) {
2    width = width || 200; // почти все значения - по умолчанию
3    height = height || 100;
4   
5    title = title || "Предупреждение" ;
6
7    //...
8 }

The showWarning function allows showWarning to specify the width and height of the width, height , title of the title , the contents of the contents and creates an additional button if showYesNo == true . Most of these parameters have a default value.

In the example above, the default values ​​are:

  • width = 200 ,
  • height = 100 ,
  • title = "Предупреждение" .

If the optional parameter is in the middle of the list of arguments, then null is usually used to pass "default values":

// width, height, title - по умолчанию
showWarning( null , null , null , "Предупреждение" , true );

The disadvantage of such a call is that the order of the arguments is easy to forget or confuse. In addition, the "holes" in the list of arguments - it is ugly.

Usually the optional parameters are transferred to the end of the list, but if there are most of them, then this is not possible.

Named arguments (keyword arguments, named arguments) exist in Python, Ruby, and many languages ​​to solve this problem.

In JavaScript, named parameters are implemented using an object. Instead of the argument list, an object is passed with parameters , like this:

1 function showWarning(options) {
2    var width = options.width || 200; width = options.width || 200; // по умолчанию
3    var height = options.height || 100; height = options.height || 100;
4   
5    var title = options.title || "Предупреждение" ;
6
7    // ...
8 }

Calling this function is very easy. It is enough to pass an object of arguments, specifying in it only the ones needed:

1 showWarning({
2    contents: "Вы вызвали функцию" ,
3    showYesNo: true
4 });

Another bonus besides the beautiful record is the possibility of reusing the argument object:

01 var opts = {
02    width: 400,
03    height: 200,
04    contents: "Текст" ,
05    showYesNo: true
06 };
07
08 showWarning(opts);
09
10 opts.contents = "Другой текст" ;
11
12 showWarning(opts); // не нужно копировать остальные аргументы в вызов

Named arguments are used in most JavaScript frameworks.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone