]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/rules/no-new-func.md
bump version to 8.4.0-3
[pve-eslint.git] / eslint / docs / rules / no-new-func.md
CommitLineData
eb39fafa
DC
1# Disallow Function Constructor (no-new-func)
2
609c276f 3It's possible to create functions in JavaScript from strings at runtime using the `Function` constructor, such as:
eb39fafa
DC
4
5```js
6var x = new Function("a", "b", "return a + b");
609c276f
TL
7var x = Function("a", "b", "return a + b");
8var x = Function.call(null, "a", "b", "return a + b");
9var x = Function.apply(null, ["a", "b", "return a + b"]);
10var x = Function.bind(null, "a", "b", "return a + b")();
eb39fafa
DC
11```
12
609c276f 13This is considered by many to be a bad practice due to the difficulty in debugging and reading these types of functions. In addition, Content-Security-Policy (CSP) directives may disallow the use of eval() and similar methods for creating code from strings.
eb39fafa
DC
14
15## Rule Details
16
17This error is raised to highlight the use of a bad practice. By passing a string to the Function constructor, you are requiring the engine to parse that string much in the way it has to when you call the `eval` function.
18
19Examples of **incorrect** code for this rule:
20
21```js
22/*eslint no-new-func: "error"*/
23
24var x = new Function("a", "b", "return a + b");
25var x = Function("a", "b", "return a + b");
609c276f
TL
26var x = Function.call(null, "a", "b", "return a + b");
27var x = Function.apply(null, ["a", "b", "return a + b"]);
28var x = Function.bind(null, "a", "b", "return a + b")();
29var f = Function.bind(null, "a", "b", "return a + b"); // assuming that the result of Function.bind(...) will be eventually called.
eb39fafa
DC
30```
31
32Examples of **correct** code for this rule:
33
34```js
35/*eslint no-new-func: "error"*/
36
37var x = function (a, b) {
38 return a + b;
39};
40```
41
42## When Not To Use It
43
44In more advanced cases where you really need to use the `Function` constructor.