-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcall-apply-decorators.html
2444 lines (2373 loc) · 104 KB
/
call-apply-decorators.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">Decorators and forwarding, call/apply</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="call-apply-decorators.html" />
<link rel="icon" href="img/favicon/favicon.png" />
<meta property="og:title" content="Decorators and forwarding, call/apply" />
<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="Decorators and forwarding, call/apply"
/>
<meta name="twitter:site" content="@iliakan" />
<meta name="twitter:creator" content="@iliakan" />
<link rel="prev" href="settimeout-setinterval.html" />
<link rel="next" href="bind.html" />
<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://www.google-analytics.com/analytics.js" async></script>
<script>
ga("send", "pageview");
</script>
<script>
(window.metrika = { reachGoal: function () {} }),
(window.yandex_metrika_callbacks = [
function () {
try {
(window.metrika = new Ya.Metrika({
id: YANDEX_METRIKA_ID,
webvisor: !0,
clickmap: !0,
params: { user: window.currentUser && window.currentUser.id },
})),
metrika.trackLinks({ delay: 150 }),
window.addEventListener("error", function (r) {
window.metrika.reachGoal("JSERROR", {
src:
(r.filename || r.errorUrl) +
": " +
(r.lineno || r.errorLine),
stack: r.stack || (r.error && r.error.stack),
message: r.message,
});
});
} catch (r) {}
},
]);
</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="Decorators and forwarding, call/apply" />
<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">
<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/call-apply-decorators"
><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="call-apply-decorators.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/call-apply-decorators"
><span class="supported-langs__brief">ES</span
><span>Español</span></a
>
</li>
call-apply-decorators"
><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/call-apply-decorators"
><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/call-apply-decorators"
><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/call-apply-decorators"
><span class="supported-langs__brief">KO</span
><span>한국어</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href=call-apply-decorators"
><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/call-apply-decorators"
><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/call-apply-decorators"
><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
>
</div>
</div>
</div>
<div class="tablet-menu__line">
<div class="tablet-menu__content">
<div class="share-icons">
<span class="share-icons__title">Share</span
>2Fcall-apply-decorators"
rel="nofollow"
></a
>2Fcall-apply-decorators
<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/call-apply-decorators"
>
عربي
</option>
<option
value="https://javascript.info/call-apply-decorators"
selected
>
English
</option>
<option
value="https://es.javascript.info/call-apply-decorators"
>
Español
</option>
<option
value="https://fr.javascript.info/call-apply-decorators"
>
Français
</option>
<option
value="https://it.javascript.info/call-apply-decorators"
>
Italiano
</option>
<option
value="https://ja.javascript.info/call-apply-decorators"
>
日本語
</option>
<option
value="https://ko.javascript.info/call-apply-decorators"
>
한국어
</option>
<option
value=call-apply-decorators"
call-apply-decorators"
call-apply-decorators"
</select>
</div>
</div>
</div>
<progress
class="tutorial-progress"
data-sticky
value="57"
max="92"
data-tooltip="Lesson 57 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 13th May 2021"
>
<div class="updated-at__content">13th May 2021</div>
</div>
</div>
<h1 class="main__header-title">
Decorators and forwarding, call/apply
</h1>
</div>
</header>
<div class="content">
<article
class="formatted"
itemscope
itemtype="http://schema.org/TechArticle"
>
<meta
itemprop="name"
content="Decorators and forwarding, call/apply"
/>
<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>
JavaScript gives exceptional flexibility when dealing with
functions. They can be passed around, used as objects, and
now we’ll see how to <em>forward</em> calls between them and
<em>decorate</em> them.
</p>
<h2>
<a
class="main__anchor"
name="transparent-caching"
href="call-apply-decorators.html#transparent-caching"
>Transparent caching</a
>
</h2>
<p>
Let’s say we have a function <code>slow(x)</code> which is
CPU-heavy, but its results are stable. In other words, for
the same <code>x</code> it always returns the same result.
</p>
<p>
If the function is called often, we may want to cache
(remember) the results to avoid spending extra-time on
recalculations.
</p>
<p>
But instead of adding that functionality into
<code>slow()</code> we’ll create a wrapper function, that
adds caching. As we’ll see, there are many benefits of doing
so.
</p>
<p>Here’s the code, and explanations follow:</p>
<div id="5fdynm3f4s" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="call-apply-decorators.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 slow(x) {
// there can be a heavy CPU-intensive job here
alert(`Called with ${x}`);
return x;
}
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) { // if there's such key in cache
return cache.get(x); // read the result from it
}
let result = func(x); // otherwise call func
cache.set(x, result); // and cache (remember) the result
return result;
};
}
slow = cachingDecorator(slow);
alert( slow(1) ); // slow(1) is cached and the result returned
alert( "Again: " + slow(1) ); // slow(1) result returned from cache
alert( slow(2) ); // slow(2) is cached and the result returned
alert( "Again: " + slow(2) ); // slow(2) result returned from cache</code></pre>
</div>
</div>
</div>
<p>
In the code above <code>cachingDecorator</code> is a
<em>decorator</em>: a special function that takes another
function and alters its behavior.
</p>
<p>
The idea is that we can call
<code>cachingDecorator</code> for any function, and it will
return the caching wrapper. That’s great, because we can
have many functions that could use such a feature, and all
we need to do is to apply <code>cachingDecorator</code> to
them.
</p>
<p>
By separating caching from the main function code we also
keep the main code simpler.
</p>
<p>
The result of <code>cachingDecorator(func)</code> is a
“wrapper”: <code>function(x)</code> that “wraps” the call of
<code>func(x)</code> into caching logic:
</p>
<figure>
<div class="image" style="width: 458px">
<div
class="image__ratio"
style="padding-top: 56.76855895196506%"
></div>
<object
type="image/svg+xml"
data="article/call-apply-decorators/decorator-makecaching-wrapper.svg"
width="458"
height="260"
class="image__image"
>
<img
src="article/call-apply-decorators/decorator-makecaching-wrapper.svg"
alt=""
width="458"
height="260"
/>
</object>
</div>
</figure>
<p>
From an outside code, the wrapped <code>slow</code> function
still does the same. It just got a caching aspect added to
its behavior.
</p>
<p>
To summarize, there are several benefits of using a separate
<code>cachingDecorator</code> instead of altering the code
of <code>slow</code> itself:
</p>
<ul>
<li>
The <code>cachingDecorator</code> is reusable. We can
apply it to another function.
</li>
<li>
The caching logic is separate, it did not increase the
complexity of <code>slow</code> itself (if there was any).
</li>
<li>
We can combine multiple decorators if needed (other
decorators will follow).
</li>
</ul>
<h2>
<a
class="main__anchor"
name="using-func-call-for-the-context"
href="call-apply-decorators.html#using-func-call-for-the-context"
>Using “func.call” for the context</a
>
</h2>
<p>
The caching decorator mentioned above is not suited to work
with object methods.
</p>
<p>
For instance, in the code below
<code>worker.slow()</code> stops working after the
decoration:
</p>
<div
id="ks1maa1ca6"
data-trusted="1"
class="code-example"
data-highlight='[{"start":30,"end":30},{"start":20,"end":20}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="call-apply-decorators.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>// we'll make worker.slow caching
let worker = {
someMethod() {
return 1;
},
slow(x) {
// scary CPU-heavy task here
alert("Called with " + x);
return x * this.someMethod(); // (*)
}
};
// same code as before
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) {
return cache.get(x);
}
let result = func(x); // (**)
cache.set(x, result);
return result;
};
}
alert( worker.slow(1) ); // the original method works
worker.slow = cachingDecorator(worker.slow); // now make it caching
alert( worker.slow(2) ); // Whoops! Error: Cannot read property 'someMethod' of undefined</code></pre>
</div>
</div>
</div>
<p>
The error occurs in the line <code>(*)</code> that tries to
access <code>this.someMethod</code> and fails. Can you see
why?
</p>
<p>
The reason is that the wrapper calls the original function
as <code>func(x)</code> in the line <code>(**)</code>. And,
when called like that, the function gets
<code>this = undefined</code>.
</p>
<p>We would observe a similar symptom if we tried to run:</p>
<div id="fscc47509n" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>let func = worker.slow;
func(2);</code></pre>
</div>
</div>
</div>
<p>
So, the wrapper passes the call to the original method, but
without the context <code>this</code>. Hence the error.
</p>
<p>Let’s fix it.</p>
<p>
There’s a special built-in function method
<a
href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call"
>func.call(context, …args)</a
>
that allows to call a function explicitly setting
<code>this</code>.
</p>
<p>The syntax is:</p>
<div id="wqcy1tfzuv" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>func.call(context, arg1, arg2, ...)</code></pre>
</div>
</div>
</div>
<p>
It runs <code>func</code> providing the first argument as
<code>this</code>, and the next as the arguments.
</p>
<p>To put it simply, these two calls do almost the same:</p>
<div id="kfhioteh2h" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>func(1, 2, 3);
func.call(obj, 1, 2, 3)</code></pre>
</div>
</div>
</div>
<p>
They both call <code>func</code> with arguments
<code>1</code>, <code>2</code> and <code>3</code>. The only
difference is that <code>func.call</code> also sets
<code>this</code> to <code>obj</code>.
</p>
<p>
As an example, in the code below we call
<code>sayHi</code> in the context of different objects:
<code>sayHi.call(user)</code> runs
<code>sayHi</code> providing <code>this=user</code>, and the
next line sets <code>this=admin</code>:
</p>
<div id="7kq74324qj" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="call-apply-decorators.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(this.name);
}
let user = { name: "John" };
let admin = { name: "Admin" };
// use call to pass different objects as "this"
sayHi.call( user ); // John
sayHi.call( admin ); // Admin</code></pre>
</div>
</div>
</div>
<p>
And here we use <code>call</code> to call
<code>say</code> with the given context and phrase:
</p>
<div id="yt2i41ff8z" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="call-apply-decorators.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 say(phrase) {
alert(this.name + ': ' + phrase);
}
let user = { name: "John" };
// user becomes this, and "Hello" becomes the first argument
say.call( user, "Hello" ); // John: Hello</code></pre>
</div>
</div>
</div>
<p>
In our case, we can use <code>call</code> in the wrapper to
pass the context to the original function:
</p>
<div
id="3r3hfzu53y"
data-trusted="1"
class="code-example"
data-highlight='[{"start":17,"end":17}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="call-apply-decorators.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 worker = {
someMethod() {
return 1;
},
slow(x) {
alert("Called with " + x);
return x * this.someMethod(); // (*)
}
};
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) {
return cache.get(x);
}
let result = func.call(this, x); // "this" is passed correctly now
cache.set(x, result);
return result;
};
}
worker.slow = cachingDecorator(worker.slow); // now make it caching
alert( worker.slow(2) ); // works
alert( worker.slow(2) ); // works, doesn't call the original (cached)</code></pre>
</div>
</div>
</div>
<p>Now everything is fine.</p>
<p>
To make it all clear, let’s see more deeply how
<code>this</code> is passed along:
</p>
<ol>
<li>
After the decoration <code>worker.slow</code> is now the
wrapper <code>function (x) { ... }</code>.
</li>
<li>
So when <code>worker.slow(2)</code> is executed, the
wrapper gets <code>2</code> as an argument and
<code>this=worker</code> (it’s the object before dot).
</li>
<li>
Inside the wrapper, assuming the result is not yet cached,
<code>func.call(this, x)</code> passes the current
<code>this</code> (<code>=worker</code>) and the current
argument (<code>=2</code>) to the original method.
</li>
</ol>
<h2>
<a
class="main__anchor"
name="going-multi-argument"
href="call-apply-decorators.html#going-multi-argument"
>Going multi-argument</a
>
</h2>
<p>
Now let’s make <code>cachingDecorator</code> even more
universal. Till now it was working only with single-argument
functions.
</p>
<p>
Now how to cache the multi-argument
<code>worker.slow</code> method?
</p>
<div id="69h3c13xla" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="codebox__code" data-code="1">
<pre
class="line-numbers language-javascript"
><code>let worker = {
slow(min, max) {
return min + max; // scary CPU-hogger is assumed
}
};
// should remember same-argument calls
worker.slow = cachingDecorator(worker.slow);</code></pre>
</div>
</div>
</div>
<p>
Previously, for a single argument <code>x</code> we could
just <code>cache.set(x, result)</code> to save the result
and <code>cache.get(x)</code> to retrieve it. But now we
need to remember the result for a
<em>combination of arguments</em> <code>(min,max)</code>.
The native <code>Map</code> takes single value only as the
key.
</p>
<p>There are many solutions possible:</p>
<ol>
<li>
Implement a new (or use a third-party) map-like data
structure that is more versatile and allows multi-keys.
</li>
<li>
Use nested maps: <code>cache.set(min)</code> will be a
<code>Map</code> that stores the pair
<code>(max, result)</code>. So we can get
<code>result</code> as
<code>cache.get(min).get(max)</code>.
</li>
<li>
Join two values into one. In our particular case we can
just use a string <code>"min,max"</code> as the
<code>Map</code> key. For flexibility, we can allow to
provide a <em>hashing function</em> for the decorator,
that knows how to make one value from many.
</li>
</ol>
<p>
For many practical applications, the 3rd variant is good
enough, so we’ll stick to it.
</p>
<p>
Also we need to pass not just <code>x</code>, but all
arguments in <code>func.call</code>. Let’s recall that in a
<code>function()</code> we can get a pseudo-array of its
arguments as <code>arguments</code>, so
<code>func.call(this, x)</code> should be replaced with
<code>func.call(this, ...arguments)</code>.
</p>
<p>Here’s a more powerful <code>cachingDecorator</code>:</p>
<div
id="4xrw9wodg8"
data-trusted="1"
class="code-example"
data-highlight='[{"start":15,"end":15},{"start":10,"end":10}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="call-apply-decorators.html#"
title="open in sandbox"
target="_blank"