-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfunction-object.html
1929 lines (1879 loc) · 80 KB
/
function-object.html
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<script>
window.currentUser = null;
</script>
<script>
window.rateUsdToNative = 1;
</script>
<title itemprop="name">Function object, NFE</title>
<link href="pack/styles.93b05845f313a968119b.css" rel="stylesheet" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, user-scalable=yes, minimum-scale=1.0"
/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<script>
if (window.devicePixelRatio > 1)
document.cookie =
"pixelRatio=" +
window.devicePixelRatio +
";path=/;expires=Tue, 19 Jan 2038 03:14:07 GMT";
</script>
<link
href="https://fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic"
rel="stylesheet"
/>
<link
rel="apple-touch-icon-precomposed"
<link
rel="canonical"
href="function-object.html"
/>
<link rel="icon" href="img/favicon/favicon.png" />
<meta
itemprop="image"
content="https://javascript.info/img/site_preview_en_512x512.png"
/>
<meta property="og:title" content="Function object, NFE" />
<meta
property="og:image"
content="https://javascript.info/img/site_preview_en_1200x630.png"
/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="fb:admins" content="100001562528165" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Function object, NFE" />
<meta name="twitter:site" content="@iliakan" />
<meta name="twitter:creator" content="@iliakan" />
<link rel="prev" href="global-object.html" />
<link rel="next" href="new-function.html" />
<script>
window.GA_ID = "UA-2056213-15";
</script>
<script>
window.YANDEX_METRIKA_ID = 32184394;
</script>
<script>
(window.GoogleAnalyticsObject = "ga"),
(window.ga = function () {
window.ga.q.push(arguments);
}),
(window.ga.q = []),
(window.ga.l = Date.now()),
ga("create", GA_ID, "auto"),
window.GTM_ID && ga("require", GTM_ID),
window.currentUser
? ga("set", "&uid", currentUser.id)
: ga("set", "anonymizeIp", !0),
window.addEventListener("error", function (e) {
var r = (e.filename || e.errorUrl) + ": " + (e.lineno || e.errorLine),
n = e.stack || (e.error && e.error.stack);
ga("send", "exception", {
exDescription: e.message + " " + r + " " + n,
exFatal: !0,
});
});
</script>
<script src="https://mc.yandex.ru/metrika/watch.js" async></script>
<script>
window.RECAPTCHA_ID = "6LfmLAEVAAAAAJMykMnf7aY8nkyTRmYi2ynx51R1";
</script>
<script src="pack/init.810c8da2b4eed830d2da.js"></script>
<script src="pack/head.282ce219a840c583fa6d.js" defer></script>
<meta property="og:title" content="Function object, NFE" />
<meta property="og:type" content="article" />
<script src="pack/tutorial.dd771765a083d97231c4.js" defer></script>
<script src="pack/footer.ce9ac5e9c03240648299.js" defer></script>
</head>
<body class="no-icons">
<script>
window.lang = "en";
</script>
<script>
{
let t = navigator.languages || [];
t = t.map((t) => t.toLowerCase());
let o,
a,
n = [];
for (let o of window.langs)
for (let a of t)
if (a === o.code || a.startsWith(o.code + "-")) {
n.push(o);
break;
}
if ("en" === lang) {
let t = n.find((t) => "en" != t.code);
t &&
"ru" != t.code &&
((o = `\n According to your browser language headers, you know ${t.name}. Please help to <a href="https://github.com/javascript-tutorial/${t.code}.javascript.info#readme">translate the tutorial</a> into your language!\n Thank you!\n `),
(a = "notify-translate-tutorial"));
} else if ("ru" != lang) {
n.find((t) => "en" == t.code) &&
((o = `\n According to your browser headers, you know English. Please help to <a href="https://github.com/javascript-tutorial/${lang}.javascript.info#readme">translate the tutorial</a>.\n Thank you!\n `),
(a = "notify-translate-tutorial-local"));
}
if (o) {
let t = `<div class="notification notification_top notification_info sitetoolbar__notification" style="display:none" id="${a}">\n <div class="notification__content">${o}</div>\n <button class="notification__close" title="Close"></button>\n </div>`;
document.write(t), showTopNotification();
}
}
</script>
<div class="sitetoolbar__content">
<div class="sitetoolbar__lang-switcher">
<button class="sitetoolbar__dropdown-button" data-dropdown-toggler>
EN
</button>
<div class="sitetoolbar__dropdown-wrap">
<div class="sitetoolbar__dropdown-body">
<div class="sitetoolbar__lang-switcher-body">
<div class="supported-langs supported-langs_toolbar">
<div class="supported-langs__container">
<ul class="supported-langs__list" style="height: 200px">
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://ar.javascript.info/function-object"
><span class="supported-langs__brief">AR</span
><span>عربي</span></a
>
</li>
<li
class="
supported-langs__item supported-langs__item_current
"
>
<a
class="supported-langs__link"
href="function-object.html"
><span class="supported-langs__brief">EN</span
><span>English</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://es.javascript.info/function-object"
><span class="supported-langs__brief">ES</span
><span>Español</span></a
>
</li>
function-object"
><span class="supported-langs__brief">FR</span
><span>Français</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://it.javascript.info/function-object"
><span class="supported-langs__brief">IT</span
><span>Italiano</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://ja.javascript.info/function-object"
><span class="supported-langs__brief">JA</span
><span>日本語</span></a
>
</li>
</ul>
<ul class="supported-langs__list" style="height: 128px">
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://ko.javascript.info/function-object"
><span class="supported-langs__brief">KO</span
><span>한국어</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href=function-object"
><span class="supported-langs__brief">RU</span
><span>Русский</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://tr.javascript.info/function-object"
><span class="supported-langs__brief">TR</span
><span>Türkçe</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://zh.javascript.info/function-object"
><span class="supported-langs__brief">ZH</span
><span>简体中文</span></a
>
</li>
</ul>
</div>
<div class="supported-langs__text">
<p>
We want to make this open-source project available for
people all around the world.
</p>
<p>
<a href="translate.html">Help to translate</a>
the content of this tutorial to your language!
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sitetoolbar__logo-wrap">
<a
class="sitetoolbar__link sitetoolbar__link_logo"
href="index.html"
><img
class="sitetoolbar__logo sitetoolbar__logo_normal"
src="img/sitetoolbar__logo_en.svg"
width="200"
alt=""
role="presentation"
/><img
class="sitetoolbar__logo sitetoolbar__logo_small"
src="img/sitetoolbar__logo_small_en.svg"
width="70"
alt=""
role="presentation"
/>
<script>
Array.prototype.forEach.call(
document.querySelectorAll("img.sitetoolbar__logo"),
function (e) {
let t = document.createElement("object");
(t.type = "image/svg+xml"),
(t.className = e.className),
(t.style.cssText = "left:0;top:0;position:absolute"),
(t.onload = function () {
(t.onload = null), (e.style.visibility = "hidden");
}),
(t.data = e.src),
e.parentNode.insertBefore(t, e);
}
);
</script></a
>
<form
class="sitetoolbar__search"
method="GET"
action="https://javascript.info/search"
>
<button
class="sitetoolbar__search-toggle"
type="button"
></button>
<div class="sitetoolbar__search-input">
<div class="text-input">
<input
class="text-input__control"
name="query"
placeholder="Search on Javascript.info"
required="required"
type="text"
/>
</div>
<button class="sitetoolbar__find" type="submit">
Search
</button>
</div>
</form>
</div>
</div>
</div>
<div class="tablet-menu__line">
<div class="tablet-menu__content">
<div class="share-icons">
<span class="share-icons__title">Share</span
>2Ffunction-object"
rel="nofollow"
></a
>2Ffunction-object
<select
class="
tablet-menu__nav
input-select input-select input-select_small
"
onchange="if(this.value) window.location.href=this.value"
>
<option value="https://ar.javascript.info/function-object">
عربي
</option>
<option
value="https://javascript.info/function-object"
selected
>
English
</option>
<option value="https://es.javascript.info/function-object">
Español
</option>
<option value="https://fr.javascript.info/function-object">
Français
</option>
<option value="https://it.javascript.info/function-object">
Italiano
</option>
<option value="https://ja.javascript.info/function-object">
日本語
</option>
<option value="https://ko.javascript.info/function-object">
한국어
</option>
<option value=function-object">
Русский
</option>
<option value="https://tr.javascript.info/function-object">
Türkçe
</option>
<option value="https://zh.javascript.info/function-object">
简体中文
</option>
</select>
</div>
</div>
</div>
<progress
class="tutorial-progress"
data-sticky
value="54"
max="92"
data-tooltip="Lesson 54 of 92"
></progress>
</div>
<div class="page page_sidebar_on page_inner_padding">
<script>
if (localStorage.noSidebar) {
document.querySelector(".page").classList.remove("page_sidebar_on");
let e = document.querySelector(".page-wrapper");
e && e.classList.remove("page-wrapper_sidebar_on");
}
setTimeout(function () {
document
.querySelector(".page")
.classList.add("page_sidebar-animation-on");
});
</script>
<div class="page__inner">
<main class="main main_width-limit">
<header class="main__header">
<div class="main__header-inner">
<div class="main__header-group">
<ol class="breadcrumbs">
<li class="breadcrumbs__item breadcrumbs__item_home">
<a class="breadcrumbs__link" href="index.html"
><span class="breadcrumbs__hidden-text"
>Tutorial</span
></a
>
</li>
<li class="breadcrumbs__item" id="breadcrumb-1">
<a class="breadcrumbs__link" href="js.html"
><span>The JavaScript language</span></a
>
</li>
<li class="breadcrumbs__item" id="breadcrumb-2">
<a
class="breadcrumbs__link"
href="advanced-functions.html"
><span>Advanced working with functions</span></a
>
</li>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"name": "Tutorial",
"item": "https://javascript.info/"
},
{
"@type": "ListItem",
"position": 2,
"name": "The JavaScript language",
"item": "https://javascript.info/js"
},
{
"@type": "ListItem",
"position": 3,
"name": "Advanced working with functions",
"item": "https://javascript.info/advanced-functions"
}
]
}
</script>
</ol>
<div
class="updated-at"
data-tooltip="Last updated at 24th March 2021"
>
<div class="updated-at__content">24th March 2021</div>
</div>
</div>
<h1 class="main__header-title">Function object, NFE</h1>
</div>
</header>
<div class="content">
<article
class="formatted"
itemscope
itemtype="http://schema.org/TechArticle"
>
<meta itemprop="name" content="Function object, NFE" />
<div
itemprop="author"
itemscope
itemtype="http://schema.org/Person"
>
<meta itemprop="email" content="[email protected]" /><meta
itemprop="name"
content="Ilya Kantor"
/>
</div>
<div itemprop="articleBody">
<p>
As we already know, a function in JavaScript is a value.
</p>
<p>
Every value in JavaScript has a type. What type is a
function?
</p>
<p>In JavaScript, functions are objects.</p>
<p>
A good way to imagine functions is as callable “action
objects”. We can not only call them, but also treat them as
objects: add/remove properties, pass by reference etc.
</p>
<h2>
<a
class="main__anchor"
name="the-name-property"
href="function-object.html#the-name-property"
>The “name” property</a
>
</h2>
<p>Function objects contain some useable properties.</p>
<p>
For instance, a function’s name is accessible as the “name”
property:
</p>
<div id="ji9husi26v" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function sayHi() {
alert("Hi");
}
alert(sayHi.name); // sayHi</code></pre>
</div>
</div>
</div>
<p>
What’s kind of funny, the name-assigning logic is smart. It
also assigns the correct name to a function even if it’s
created without one, and then immediately assigned:
</p>
<div id="g79uydanrc" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>let sayHi = function() {
alert("Hi");
};
alert(sayHi.name); // sayHi (there's a name!)</code></pre>
</div>
</div>
</div>
<p>
It also works if the assignment is done via a default value:
</p>
<div id="4t9jmz61l3" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function f(sayHi = function() {}) {
alert(sayHi.name); // sayHi (works!)
}
f();</code></pre>
</div>
</div>
</div>
<p>
In the specification, this feature is called a “contextual
name”. If the function does not provide one, then in an
assignment it is figured out from the context.
</p>
<p>Object methods have names too:</p>
<div id="vo8dnc4ujs" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>let user = {
sayHi() {
// ...
},
sayBye: function() {
// ...
}
}
alert(user.sayHi.name); // sayHi
alert(user.sayBye.name); // sayBye</code></pre>
</div>
</div>
</div>
<p>
There’s no magic though. There are cases when there’s no way
to figure out the right name. In that case, the name
property is empty, like here:
</p>
<div id="bfw86yhgyz" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>// function created inside array
let arr = [function() {}];
alert( arr[0].name ); // <empty string>
// the engine has no way to set up the right name, so there is none</code></pre>
</div>
</div>
</div>
<p>In practice, however, most functions do have a name.</p>
<h2>
<a
class="main__anchor"
name="the-length-property"
href="function-object.html#the-length-property"
>The “length” property</a
>
</h2>
<p>
There is another built-in property “length” that returns the
number of function parameters, for instance:
</p>
<div id="vtjb4ku9ob" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function f1(a) {}
function f2(a, b) {}
function many(a, b, ...more) {}
alert(f1.length); // 1
alert(f2.length); // 2
alert(many.length); // 2</code></pre>
</div>
</div>
</div>
<p>Here we can see that rest parameters are not counted.</p>
<p>
The <code>length</code> property is sometimes used for
<a href="https://en.wikipedia.org/wiki/Type_introspection"
>introspection</a
>
in functions that operate on other functions.
</p>
<p>
For instance, in the code below the
<code>ask</code> function accepts a <code>question</code> to
ask and an arbitrary number of
<code>handler</code> functions to call.
</p>
<p>
Once a user provides their answer, the function calls the
handlers. We can pass two kinds of handlers:
</p>
<ul>
<li>
A zero-argument function, which is only called when the
user gives a positive answer.
</li>
<li>
A function with arguments, which is called in either case
and returns an answer.
</li>
</ul>
<p>
To call <code>handler</code> the right way, we examine the
<code>handler.length</code> property.
</p>
<p>
The idea is that we have a simple, no-arguments handler
syntax for positive cases (most frequent variant), but are
able to support universal handlers as well:
</p>
<div id="p3litd6sha" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function ask(question, ...handlers) {
let isYes = confirm(question);
for(let handler of handlers) {
if (handler.length == 0) {
if (isYes) handler();
} else {
handler(isYes);
}
}
}
// for positive answer, both handlers are called
// for negative answer, only the second one
ask("Question?", () => alert('You said yes'), result => alert(result));</code></pre>
</div>
</div>
</div>
<p>
This is a particular case of so-called
<a
href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)"
>polymorphism</a
>
– treating arguments differently depending on their type or,
in our case depending on the <code>length</code>. The idea
does have a use in JavaScript libraries.
</p>
<h2>
<a
class="main__anchor"
name="custom-properties"
href="function-object.html#custom-properties"
>Custom properties</a
>
</h2>
<p>We can also add properties of our own.</p>
<p>
Here we add the <code>counter</code> property to track the
total calls count:
</p>
<div
id="9wducrww74"
data-trusted="1"
class="code-example"
data-highlight='[{"start":3,"end":4}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function sayHi() {
alert("Hi");
// let's count how many times we run
sayHi.counter++;
}
sayHi.counter = 0; // initial value
sayHi(); // Hi
sayHi(); // Hi
alert( `Called ${sayHi.counter} times` ); // Called 2 times</code></pre>
</div>
</div>
</div>
<div class="important important_warn">
<div class="important__header">
<span class="important__type"
>A property is not a variable</span
>
</div>
<div class="important__content">
<p>
A property assigned to a function like
<code>sayHi.counter = 0</code> does <em>not</em> define
a local variable <code>counter</code> inside it. In
other words, a property <code>counter</code> and a
variable <code>let counter</code> are two unrelated
things.
</p>
<p>
We can treat a function as an object, store properties
in it, but that has no effect on its execution.
Variables are not function properties and vice versa.
These are just parallel worlds.
</p>
</div>
</div>
<p>
Function properties can replace closures sometimes. For
instance, we can rewrite the counter function example from
the chapter
<a href="closure.html">Variable scope, closure</a> to use a
function property:
</p>
<div id="88hyrg3zku" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function makeCounter() {
// instead of:
// let count = 0
function counter() {
return counter.count++;
};
counter.count = 0;
return counter;
}
let counter = makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1</code></pre>
</div>
</div>
</div>
<p>
The <code>count</code> is now stored in the function
directly, not in its outer Lexical Environment.
</p>
<p>Is it better or worse than using a closure?</p>
<p>
The main difference is that if the value of
<code>count</code> lives in an outer variable, then external
code is unable to access it. Only nested functions may
modify it. And if it’s bound to a function, then such a
thing is possible:
</p>
<div
id="vyttbmjtqv"
data-trusted="1"
class="code-example"
data-highlight='[{"start":13,"end":14}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="function-object.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="function-object.html#"
title="open in sandbox"
target="_blank"
data-action="edit"
class="toolbar__button toolbar__button_edit"
></a>
</div>
</div>
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>function makeCounter() {
function counter() {
return counter.count++;
};
counter.count = 0;
return counter;
}
let counter = makeCounter();
counter.count = 10;
alert( counter() ); // 10</code></pre>
</div>
</div>
</div>
<p>So the choice of implementation depends on our aims.</p>
<h2>
<a