Skip to content

Commit

Permalink
error if method is an arrow function expression and uses this or `a…
Browse files Browse the repository at this point in the history
…rguments` (#179)
  • Loading branch information
Rich-Harris committed Dec 11, 2016
1 parent fd77efa commit a6c648b
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/validate/js/propValidators/methods.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import checkForDupes from '../utils/checkForDupes.js';
import checkForComputedKeys from '../utils/checkForComputedKeys.js';
import usesThisOrArguments from '../utils/usesThisOrArguments.js';

const builtin = {
set: true,
Expand All @@ -23,5 +24,11 @@ export default function methods ( validator, prop ) {
if ( builtin[ prop.key.name ] ) {
validator.error( `Cannot overwrite built-in method '${prop.key.name}'` );
}

if ( prop.value.type === 'ArrowFunctionExpression' ) {
if ( usesThisOrArguments( prop.value.body ) ) {
validator.error( `Method '${prop.key.name}' should be a function expression, not an arrow function expression`, prop.start );
}
}
});
}
24 changes: 24 additions & 0 deletions src/validate/js/utils/usesThisOrArguments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { walk } from 'estree-walker';
import isReference from '../../../utils/isReference.js';

export default function usesThisOrArguments ( node ) {
let result = false;

walk( node, {
enter ( node ) {
if ( result || node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' ) {
return this.skip();
}

if ( node.type === 'ThisExpression' ) {
result = true;
}

if ( node.type === 'Identifier' && isReference( node ) && node.name === 'arguments' ) {
result = true;
}
}
});

return result;
}
1 change: 1 addition & 0 deletions test/validator/method-arrow-no-this/errors.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
9 changes: 9 additions & 0 deletions test/validator/method-arrow-no-this/input.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<button on:click='foo()'></button>

<script>
export default {
methods: {
foo: () => console.log( 'foo' )
}
};
</script>
8 changes: 8 additions & 0 deletions test/validator/method-arrow-this/errors.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[{
"message": "Method 'foo' should be a function expression, not an arrow function expression",
"pos": 79,
"loc": {
"line": 6,
"column": 3
}
}]
11 changes: 11 additions & 0 deletions test/validator/method-arrow-this/input.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<button on:click='foo()'></button>

<script>
export default {
methods: {
foo: () => {
this.set({ a: 1 });
}
}
};
</script>

0 comments on commit a6c648b

Please sign in to comment.