google / google/closure-compiler

Incorrect code generated when using this in an object literal's method

Open
#2,827 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

When a method on an object literal references `this`, the compiler produces the wrong output in advanced mode. [Demo link](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520ADVANCED_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250Aconst%2520foo%2520%253D%2520%257B%250A%2520%2520%252F**%2520%2540type%2520%257Bnumber%257D%2520*%252F%250A%2520%2520baz%253A%25200%252C%250A%2520%2520%250A%2520%2520%252F**%2520%2540this%2520%257BObject%257D%2520*%252F%250A%2520%2520bar%253A%2520function(x)%2520%257B%250A%2520%2520%2520%2520this.baz%2520%253D%2520x%253B%250A%2520%2520%257D%250A%257D%250A%250Afoo.bar(4)%253B%250Aconsole.log(foo.baz)%253B)

Demo input:
```
const foo = {
/** @type {number} */
baz: 0,

/** @this {Object} */
bar: function(x) {
this.baz = x;
}
}

foo.bar(4);
console.log(foo.baz);
```

Output in simple mode (correctly prints "4"):
```
var foo={baz:0,bar:function(a){this.baz=a}};foo.bar(4);console.log(foo.baz);
```

Output in advanced mode (incorrect):
```
console.log(0);
```

As a workaround, changing `this.baz = x` to `foo.baz = x` works fine.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.