Evaluate computed class props only once (#6240) (#6466)

Previously, computed class properties would be evaluated every time a
new instance of the class was created. This means the property name
may have changed between different instances, as well as potential side
effects.

This commit fixes this by storing the computed value in a separate
variable.
This commit is contained in:
Qantas94Heavy
2017-10-13 21:19:48 +11:00
committed by Nicolò Ribaudo
parent bfa167cc21
commit 5f285c1034
7 changed files with 98 additions and 6 deletions

View File

@@ -96,6 +96,20 @@ export default function({ types: t }, options) {
if (isStatic) {
nodes.push(buildClassProperty(ref, propNode, path.scope));
} else {
// Make sure computed property names are only evaluated once (upon
// class definition).
if (propNode.computed) {
const ident = path.scope.generateUidIdentifierBasedOnNode(
propNode.key,
);
nodes.push(
t.variableDeclaration("var", [
t.variableDeclarator(ident, propNode.key),
]),
);
propNode.key = ident;
}
instanceBody.push(
buildClassProperty(t.thisExpression(), propNode, path.scope),
);