1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
---
title: Default parameters
slug: Web/JavaScript/Reference/Functions/Default_parameters
translation_of: Web/JavaScript/Reference/Functions/Default_parameters
---
<div>{{jsSidebar("Functions")}}</div>
<div dir="rtl"><strong>הצבת פרמטר ברירת מחדל לפונקציה </strong>מאפשר רישום של ערך ראשוני בזמן הגדרת הפונקציה, כך שאם לא מועבר ערך בקריאה (הפעלה) של הפונקציה, או שמעבירים <code>undefined</code> כערך, הערך הראשוני שהוגדר כברירת מחדל ישמש בתור הפרמטר של הפונקציה.</div>
<p> </p>
<h2 dir="rtl" id="שימוש_בשפה"><strong>שימוש בשפה</strong></h2>
<pre class="syntaxbox">function [<em>name</em>]([<em>param1</em>[ = defaultValue1 ][, ..., <em>paramN</em>[ = defaultValueN ]]]) {
<em>statements</em>
}
</pre>
<h2 dir="rtl" id="תיאור_שימושיות"><strong>תיאור שימושיות</strong></h2>
<p dir="rtl">הערך ראשוני של פרמטר בפונקציה ב JavaScript שווה ל <code>undefined</code>. אומנם ישנם מקרים בהם זה יכול להיות נוח להציב ערך שונה כערך ראשוני לפרמטר של הפונקציה, כך שהערך יוגדר מראש ביצירת הפונקציה. ופה אנחנו נעזרים בהצבת פרמטר ברירת מחדל לפונקציה.</p>
<p dir="rtl">האסטרטגיה הכללית שהשתמשו בה לפני פרמטר ברירת המחדל, היתה בדיקה שנכללה בתוך גוף הפונקציה ובדקה אם הפרמטר מכיל ערך או שהוא אינו מוגדר, ולא נעשה בו שימוש בקריאה לפונקציה. בדוגמא שלפנינו אם לא נעביר ערך ל <code>b</code> בקריאה לפונקציה (בהפעלה שלה, בכל הפעלה לש פונקציה אנחנו קוראים לה מהזיכרון), היא תקבל ערך לא מוגדר (<code>undefined</code>) וכאשר תיקראו לפונקציה <code>multiply</code> כדי לחשב את <code>a*b</code> התוצאה תהיה <code>NaN</code>. לשם כך השורה השניה בפונקציה בודקת אם קיים בפרמטר <code>b</code> ערך השונה מ <code>undefined</code> ואם לא נעשה שימוש בפרמטר <code>b</code> בקריאה לפונקציה אז מציבים בו ערך ראשוני של 1:</p>
<pre class="brush: js">function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1;
return a * b;
}
multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5); // 5
</pre>
<p dir="rtl">בעזרת הצבה של פרמטר ברירת מחדל לפונקציה הניתן לשימוש מגרסה ES2015 הבדיקה בגוף הפונקציה כבר לא נחוצה. עכשיו אפשר פשוט להציב ערך ראשוני כערך ברירת מחדל בהגדרה של הפונקציה והפרמטרים שלה:</p>
<pre class="brush: js">function multiply(a, b = 1) {
return a * b;
}
multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5); // 5
</pre>
<h2 dir="rtl" id="דוגמאות"><strong>דוגמאות</strong></h2>
<h3 dir="rtl" id="קריאה_לפונקציה_עם_ערך_של_undefined_מול_ערכים_שליליים_שונים.">קריאה לפונקציה עם ערך של <code>undefined</code> מול ערכים שליליים שונים.</h3>
<p dir="rtl">בהפעלה השניה של הפונקציה בדוגמה <code>test</code> אנחנו מעבירים באופן מכוון ערך של <code>undefined</code> והפרמטר <code>num</code> עדיין מקבל את ערך ברירת המחדל שהגדרנו בעת יצירת הפונקציה <code>(num = 1)</code>. ניתן לראות בקריאות הבאות לפונקציה, כי אך ורק <code>undefined</code> זוכה להחלפה בערך ברירת המחדל ולא שום סוג של ערך שלילי אחר ( <code>num === fale!!</code> ).</p>
<pre class="brush: js">function test(num = 1) {
console.log(typeof num);
}
test(); // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)
// test with other falsy values:
test(''); // 'string' (num is set to '')
test(null); // 'object' (num is set to null)
</pre>
<h3 id="Evaluated_at_call_time">Evaluated at call time</h3>
<p>The default argument gets evaluated at call time, so unlike e.g. in Python, a new object is created each time the function is called.</p>
<pre class="brush: js">function append(value, array = []) {
array.push(value);
return array;
}
append(1); //[1]
append(2); //[2], not [1, 2]
</pre>
<p>This even applies to functions and variables:</p>
<pre class="brush: js">function callSomething(thing = something()) {
return thing;
}
function something() {
return 'sth';
}
callSomething(); //sth</pre>
<h3 id="Default_parameters_are_available_to_later_default_parameters">Default parameters are available to later default parameters</h3>
<p>Parameters already encountered are available to later default parameters:</p>
<pre class="brush: js">function singularAutoPlural(singular, plural = singular + 's',
rallyingCry = plural + ' ATTACK!!!') {
return [singular, plural, rallyingCry];
}
//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural('Gecko');
//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural('Fox', 'Foxes');
//["Deer", "Deer", "Deer ... change."]
singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \
petition the government for positive change.')
</pre>
<p>This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled.</p>
<pre class="brush: js">function go() {
return ':P';
}
function withDefaults(a, b = 5, c = b, d = go(), e = this,
f = arguments, g = this.value) {
return [a, b, c, d, e, f, g];
}
function withoutDefaults(a, b, c, d, e, f, g) {
switch (arguments.length) {
case 0:
a;
case 1:
b = 5;
case 2:
c = b;
case 3:
d = go();
case 4:
e = this;
case 5:
f = arguments;
case 6:
g = this.value;
default:
}
return [a, b, c, d, e, f, g];
}
withDefaults.call({value: '=^_^='});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
withoutDefaults.call({value: '=^_^='});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
</pre>
<h3 id="Functions_defined_inside_function_body">Functions defined inside function body</h3>
<p>Introduced in Gecko 33 {{geckoRelease(33)}}. Functions declared in the function body cannot be referred inside default parameters and throw a {{jsxref("ReferenceError")}} (currently a {{jsxref("TypeError")}} in SpiderMonkey, see {{bug(1022967)}}). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.</p>
<pre class="brush: js">// Doesn't work! Throws ReferenceError.
function f(a = go()) {
function go() { return ':P'; }
}
</pre>
<h3 id="Parameters_without_defaults_after_default_parameters">Parameters without defaults after default parameters</h3>
<p>Prior to Gecko 26 {{geckoRelease(26)}}, the following code resulted in a {{jsxref("SyntaxError")}}. This has been fixed in {{bug(777060)}} and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.</p>
<pre class="brush: js">function f(x = 1, y) {
return [x, y];
}
f(); // [1, undefined]
f(2); // [2, undefined]
</pre>
<h3 id="Destructured_parameter_with_default_value_assignment">Destructured parameter with default value assignment</h3>
<p>You can use default value assignment with the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment</a> notation:</p>
<pre class="brush: js">function f([x, y] = [1, 2], {z: z} = {z: 3}) {
return x + y + z;
}
f(); // 6</pre>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}</td>
<td>{{Spec2('ES2015')}}</td>
<td>Initial definition.</td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<div>
<p>{{Compat("javascript.functions.default_parameters")}}</p>
</div>
<h2 id="See_also">See also</h2>
<ul>
<li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values" rel="external" title="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values">Original proposal at ecmascript.org</a></li>
</ul>
|