-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnew-function.html
992 lines (975 loc) · 41.6 KB
/
new-function.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
<!DOCTYPE html>
<html lang="en">
<head>
<script>
window.currentUser = null;
</script>
<script>
window.rateUsdToNative = 1;
</script>
<title itemprop="name">The "new Function" syntax</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="new-function.html"
/>
<meta name="msapplication-TileColor" content="#222A2C" />
<meta name="msapplication-TileImage" content="/img/favicon/tileicon.png" />
<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='The "new Function" syntax' />
<meta
property="og:image"
content="https://javascript.info/img/site_preview_en_1200x630.png"
/>
<meta property="og:image:type" content="image/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='The "new Function" syntax' />
<meta name="twitter:site" content="@iliakan" />
<meta name="twitter:creator" content="@iliakan" />
<link rel="prev" href="function-object.html" />
<link rel="next" href="settimeout-setinterval.html" />
<script>
window.GA_ID = "UA-2056213-15";
</script>
<script>
window.YANDEX_METRIKA_ID = 32184394;
</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='The "new Function" syntax' />
<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/new-function"
><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="new-function.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/new-function"
><span class="supported-langs__brief">ES</span
><span>Español</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href="https://fr.javascript.info/new-function"
><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/new-function"
><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/new-function"
><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/new-function"
><span class="supported-langs__brief">KO</span
><span>한국어</span></a
>
</li>
<li class="supported-langs__item">
<a
class="supported-langs__link"
href=new-function"
><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/new-function"
><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/new-function"
><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
>2Fnew-function"
rel="nofollow"
></a
>2Fnew-function"
rel="nofollow"
></a>
</div>
</div>
</div>
<div class="tablet-menu__line">
<div class="tablet-menu__content">
<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/new-function">
عربي
</option>
<option value="https://javascript.info/new-function" selected>
English
</option>
<option value="https://es.javascript.info/new-function">
Español
</option>
<option value="https://fr.javascript.info/new-function">
Français
</option>
<option value="https://it.javascript.info/new-function">
Italiano
</option>
<option value="https://ja.javascript.info/new-function">
日本語
</option>
<option value="https://ko.javascript.info/new-function">
한국어
</option>
<option value=new-function">
Русский
</option>
<option value="https://tr.javascript.info/new-function">
Türkçe
</option>
<option value="https://zh.javascript.info/new-function">
简体中文
</option>
</select>
</div>
</div>
</div>
<progress
class="tutorial-progress"
data-sticky
value="55"
max="92"
data-tooltip="Lesson 55 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 22nd October 2020"
>
<div class="updated-at__content">22nd October 2020</div>
</div>
</div>
<h1 class="main__header-title">
The "new Function" syntax
</h1>
</div>
</header>
<div class="content">
<article
class="formatted"
itemscope
itemtype="http://schema.org/TechArticle"
>
<meta itemprop="name" content='The "new Function" syntax' />
<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>
There’s one more way to create a function. It’s rarely used,
but sometimes there’s no alternative.
</p>
<h2>
<a
class="main__anchor"
name="syntax"
href="new-function.html#syntax"
>Syntax</a
>
</h2>
<p>The syntax for creating a function:</p>
<div id="bdynzgypap" 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 = new Function ([arg1, arg2, ...argN], functionBody);</code></pre>
</div>
</div>
</div>
<p>
The function is created with the arguments
<code>arg1...argN</code> and the given
<code>functionBody</code>.
</p>
<p>
It’s easier to understand by looking at an example. Here’s a
function with two arguments:
</p>
<div id="cnerpqd7yn" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="new-function.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="new-function.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 sum = new Function('a', 'b', 'return a + b');
alert( sum(1, 2) ); // 3</code></pre>
</div>
</div>
</div>
<p>
And here there’s a function without arguments, with only the
function body:
</p>
<div id="8xk2h03312" data-trusted="1" class="code-example">
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="new-function.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="new-function.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 = new Function('alert("Hello")');
sayHi(); // Hello</code></pre>
</div>
</div>
</div>
<p>
The major difference from other ways we’ve seen is that the
function is created literally from a string, that is passed
at run time.
</p>
<p>
All previous declarations required us, programmers, to write
the function code in the script.
</p>
<p>
But <code>new Function</code> allows to turn any string into
a function. For example, we can receive a new function from
a server and then execute it:
</p>
<div id="yfi6c0xvui" 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 str = ... receive the code from a server dynamically ...
let func = new Function(str);
func();</code></pre>
</div>
</div>
</div>
<p>
It is used in very specific cases, like when we receive code
from a server, or to dynamically compile a function from a
template, in complex web-applications.
</p>
<h2>
<a
class="main__anchor"
name="closure"
href="new-function.html#closure"
>Closure</a
>
</h2>
<p>
Usually, a function remembers where it was born in the
special property <code>[[Environment]]</code>. It references
the Lexical Environment from where it’s created (we covered
that in the chapter
<a href="closure.html">Variable scope, closure</a>).
</p>
<p>
But when a function is created using
<code>new Function</code>, its
<code>[[Environment]]</code> is set to reference not the
current Lexical Environment, but the global one.
</p>
<p>
So, such function doesn’t have access to outer variables,
only to the global ones.
</p>
<div
id="b3z0ydya3t"
data-trusted="1"
class="code-example"
data-highlight='[{"start":3,"end":3}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="new-function.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="new-function.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 getFunc() {
let value = "test";
let func = new Function('alert(value)');
return func;
}
getFunc()(); // error: value is not defined</code></pre>
</div>
</div>
</div>
<p>Compare it with the regular behavior:</p>
<div
id="qr1j405rrv"
data-trusted="1"
class="code-example"
data-highlight='[{"start":8,"cols":[{"start":16,"end":22}]},{"start":3,"end":3}]'
>
<div class="codebox code-example__codebox">
<div class="toolbar codebox__toolbar">
<div class="toolbar__tool">
<a
href="new-function.html#"
title="run"
data-action="run"
class="toolbar__button toolbar__button_run"
></a>
</div>
<div class="toolbar__tool">
<a
href="new-function.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 getFunc() {
let value = "test";
let func = function() { alert(value); };
return func;
}
getFunc()(); // "test", from the Lexical Environment of getFunc</code></pre>
</div>
</div>
</div>
<p>
This special feature of <code>new Function</code> looks
strange, but appears very useful in practice.
</p>
<p>
Imagine that we must create a function from a string. The
code of that function is not known at the time of writing
the script (that’s why we don’t use regular functions), but
will be known in the process of execution. We may receive it
from the server or from another source.
</p>
<p>
Our new function needs to interact with the main script.
</p>
<p>What if it could access the outer variables?</p>
<p>
The problem is that before JavaScript is published to
production, it’s compressed using a <em>minifier</em> – a
special program that shrinks code by removing extra
comments, spaces and – what’s important, renames local
variables into shorter ones.
</p>
<p>
For instance, if a function has <code>let userName</code>,
minifier replaces it with <code>let a</code> (or another
letter if this one is occupied), and does it everywhere.
That’s usually a safe thing to do, because the variable is
local, nothing outside the function can access it. And
inside the function, minifier replaces every mention of it.
Minifiers are smart, they analyze the code structure, so
they don’t break anything. They’re not just a dumb
find-and-replace.
</p>
<p>
So if <code>new Function</code> had access to outer
variables, it would be unable to find renamed
<code>userName</code>.
</p>
<p>
<strong
>If <code>new Function</code> had access to outer
variables, it would have problems with minifiers.</strong
>
</p>
<p>
Besides, such code would be architecturally bad and prone to
errors.
</p>
<p>
To pass something to a function, created as
<code>new Function</code>, we should use its arguments.
</p>
<h2>
<a
class="main__anchor"
name="summary"
href="new-function.html#summary"
>Summary</a
>
</h2>
<p>The syntax:</p>
<div id="q4c16475qi" 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 = new Function ([arg1, arg2, ...argN], functionBody);</code></pre>
</div>
</div>
</div>
<p>
For historical reasons, arguments can also be given as a
comma-separated list.
</p>
<p>These three declarations mean the same:</p>
<div id="ncm32oxv3n" 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>new Function('a', 'b', 'return a + b'); // basic syntax
new Function('a,b', 'return a + b'); // comma-separated
new Function('a , b', 'return a + b'); // comma-separated with spaces</code></pre>
</div>
</div>
</div>
<p>
Functions created with <code>new Function</code>, have
<code>[[Environment]]</code> referencing the global Lexical
Environment, not the outer one. Hence, they cannot use outer
variables. But that’s actually good, because it insures us
from errors. Passing parameters explicitly is a much better
method architecturally and causes no problems with
minifiers.
</p>
</div>
</article>
</div>
<div class="page__nav-wrap">
<a
class="page__nav page__nav_prev"
href="function-object.html"
data-tooltip="Function object, NFE"
><span class="page__nav-text"
><span class="page__nav-text-shortcut"></span></span
><span class="page__nav-text-alternate"
>Previous lesson</span
></a
><a
class="page__nav page__nav_next"
href="settimeout-setinterval.html"
data-tooltip="Scheduling: setTimeout and setInterval"
><span class="page__nav-text"
><span class="page__nav-text-shortcut"></span></span
><span class="page__nav-text-alternate">Next lesson</span></a
>
</div>
<div class="article-tablet-foot tablet-only">
<div class="article-tablet-foot__layout">
<div class="share-icons">
<span class="share-icons__title">Share</span
><a
class="share share_tw"
s%3A%2F%2Fjavascript.info%2Fnew-function"
rel="nofollow"
></a
><a
class="share share_fb"
href="https://www.facebook.com/sharer/sharer.php?s=100&p%5Burl%5D=https%3A%2F%2Fjavascript.info%2Fnew-function"
rel="nofollow"
></a>
</div>
<div class="article-tablet-foot__map">
<a
class="map"
href="tutorial/map.html"
data-action="tutorial-map"
><span class="map__text">Tutorial map</span></a
>
</div>
</div>
</div>
<a href="new-function.html#comments" name="comments"
>Comments</a
>
</h2>
<div class="comments__read-before">
<span class="comments__read-before-link"
>read this before commenting…</span
>
<div class="comments__read-before-popup">
<div class="comments__read-before-popup-i">
<ul>
<li>
If you have suggestions what to improve - please
<a
href="https://github.com/javascript-tutorial/en.javascript.info/issues/new"
>submit a GitHub issue</a
>
or a pull request instead of commenting.
</li>
<li>
If you can't understand something in the article –
please elaborate.
</li>
<li>
To insert few words of code, use the
<code><code></code> tag, for several lines –
wrap them in <code><pre></code> tag, for more
than 10 lines – use a sandbox (<a
href="https://plnkr.co/edit/?p=preview"
>plnkr</a
>, <a href="https://jsbin.com">jsbin</a>,
<a href="http://codepen.io">codepen</a>…)
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
if (!this.page) this.page = {};
Object.assign(this.page, {
url: "https:\/\/javascript.info\/new-function",
identifier: "\/new-function",
});
};
</script>
<script>
var disqus_shortname = "javascriptinfo";
</script>
<script>
var disqus_enabled = true;
</script>
</div>
</main>
</div>
<nav class="sidebar__navigation">
<ul class="sidebar__navigation-links">
<li class="sidebar__navigation-link">
<a class="sidebar__link" href="advanced-functions.html"
>Advanced working with functions</a
>
</li>
</ul>
</nav>
<h4 class="sidebar__section-title">Lesson navigation</h4>
<nav class="sidebar__navigation">
<ul class="sidebar__navigation-links">
<li class="sidebar__navigation-link">
<a class="sidebar__link" href="new-function.html#syntax"
>Syntax</a
>
</li>
<li class="sidebar__navigation-link">
<a class="sidebar__link" href="new-function.html#closure"
>Closure</a
>
</li>
<li class="sidebar__navigation-link">
<a class="sidebar__link" href="new-function.html
</ul>
</nav>
<nav class="sidebar__navigation">
<ul class="sidebar__navigation-links">
<li class="sidebar__navigation-link">
<a class="sidebar__link" href="new-function.html#comments"
>Comments</a
>
</li>
</ul>
</nav>
</div>
<a
class="share share_tw sidebar__share"
s%3A%2F%2Fjavascript.info%2Fnew-function"
rel="nofollow"
></a
><a
class="share share_fb sidebar__share"
href="https://www.facebook.com/sharer/sharer.php?s=100&p[url]=https%3A%2F%2Fjavascript.info%2Fnew-function"
rel="nofollow"
></a>
<a
class="sidebar__link"
href="https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/06-advanced-functions/07-new-function"
rel="nofollow"
>Edit on GitHub</a
>
</div>
<div class="sidebar__section" id="sponsorBar">
<div class="sidebar__section-title" id="sponsorBarTitle"></div>
<div id="sponsorBarContent"></div>
<script>
window.initSponsorBar();
</script>
<ul class="page-footer__list">
<li class="page-footer__item page-footer__item_copy">
© 2007—2021 Ilya Kantor
</li>
<li class="page-footer__item page-footer__item_about">
<a class="page-footer__link" href="about.html">about the project</a>
</li>
<li class="page-footer__item page-footer__item_contact">
<a class="page-footer__link" href="about.html#contact-us"
>contact us</a
>
</li>
<li class="page-footer__item page-footer__item_terms">
<a class="page-footer__link" href="terms.html">terms of usage</a>
</li>
<li class="page-footer__item page-footer__item_privacy">
<a class="page-footer__link" href="privacy.html">privacy policy</a>
</li>
</ul>
</div>
</body>
</html>