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) { |
3 | height = height || 100; |
5 | title = title || "Предупреждение" ; |
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":
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; |
5 | var title = options.title || "Предупреждение" ; |
Calling this function is very easy. It is enough to pass an object of arguments, specifying in it only the ones needed:
2 | contents: "Вы вызвали функцию" , |
Another bonus besides the beautiful record is the possibility of reusing the argument object:
10 | opts.contents = "Другой текст" ; |
Named arguments are used in most JavaScript frameworks.
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone