Skip to content

Commit

Permalink
Fix: Check no-new-func on CallExpressions (fixes eslint#3145)
Browse files Browse the repository at this point in the history
Used to only check NewExpressions for Function, but according to MDN:

> Invoking the Function constructor as a function (without using the new
> operator) has the same effect as invoking it as a constructor.
  • Loading branch information
bgw committed Jul 23, 2015
1 parent a7d5e70 commit 45308aa
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
1 change: 1 addition & 0 deletions docs/rules/no-new-func.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This error is raised to highlight the use of a bad practice. By passing a string

```js
var x = new Function("a", "b", "return a + b");
var x = Function("a", "b", "return a + b");
```

The following patterns are considered okay and do not cause warnings:
Expand Down
22 changes: 17 additions & 5 deletions lib/rules/no-new-func.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,25 @@

module.exports = function(context) {

return {
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------

"NewExpression": function(node) {
if (node.callee.name === "Function") {
context.report(node, "The Function constructor is eval.");
}
/**
* Checks if the callee if the Function constructor, and if so, reports an issue.
* @param {ASTNode} node The node to check and report on
* @returns {void}
* @private
*/
function validateCallee(node) {
if (node.callee.name === "Function") {
context.report(node, "The Function constructor is eval.");
}
}

return {
"NewExpression": validateCallee,
"CallExpression": validateCallee
};

};
Expand Down
6 changes: 4 additions & 2 deletions tests/lib/rules/no-new-func.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ var eslint = require("../../../lib/eslint"),
var eslintTester = new ESLintTester(eslint);
eslintTester.addRuleTest("lib/rules/no-new-func", {
valid: [
"var a = new _function(\"b\", \"c\", \"return b+c\");"
"var a = new _function(\"b\", \"c\", \"return b+c\");",
"var a = _function(\"b\", \"c\", \"return b+c\");"
],
invalid: [
{ code: "var a = new Function(\"b\", \"c\", \"return b+c\");", errors: [{ message: "The Function constructor is eval.", type: "NewExpression"}] }
{ code: "var a = new Function(\"b\", \"c\", \"return b+c\");", errors: [{ message: "The Function constructor is eval.", type: "NewExpression"}] },
{ code: "var a = Function(\"b\", \"c\", \"return b+c\");", errors: [{ message: "The Function constructor is eval.", type: "CallExpression"}] }
]
});

0 comments on commit 45308aa

Please sign in to comment.