]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | # Disallow Function Constructor (no-new-func) |
2 | ||
609c276f | 3 | It's possible to create functions in JavaScript from strings at runtime using the `Function` constructor, such as: |
eb39fafa DC |
4 | |
5 | ```js | |
6 | var x = new Function("a", "b", "return a + b"); | |
609c276f TL |
7 | var x = Function("a", "b", "return a + b"); |
8 | var x = Function.call(null, "a", "b", "return a + b"); | |
9 | var x = Function.apply(null, ["a", "b", "return a + b"]); | |
10 | var x = Function.bind(null, "a", "b", "return a + b")(); | |
eb39fafa DC |
11 | ``` |
12 | ||
609c276f | 13 | This 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 | ||
17 | This 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 | ||
19 | Examples of **incorrect** code for this rule: | |
20 | ||
21 | ```js | |
22 | /*eslint no-new-func: "error"*/ | |
23 | ||
24 | var x = new Function("a", "b", "return a + b"); | |
25 | var x = Function("a", "b", "return a + b"); | |
609c276f TL |
26 | var x = Function.call(null, "a", "b", "return a + b"); |
27 | var x = Function.apply(null, ["a", "b", "return a + b"]); | |
28 | var x = Function.bind(null, "a", "b", "return a + b")(); | |
29 | var f = Function.bind(null, "a", "b", "return a + b"); // assuming that the result of Function.bind(...) will be eventually called. | |
eb39fafa DC |
30 | ``` |
31 | ||
32 | Examples of **correct** code for this rule: | |
33 | ||
34 | ```js | |
35 | /*eslint no-new-func: "error"*/ | |
36 | ||
37 | var x = function (a, b) { | |
38 | return a + b; | |
39 | }; | |
40 | ``` | |
41 | ||
42 | ## When Not To Use It | |
43 | ||
44 | In more advanced cases where you really need to use the `Function` constructor. |