Object.defineProperty in class constructor

99 views
Skip to first unread message

Dmitrii Tikhomirov

unread,
Oct 30, 2020, 3:53:18 PM10/30/20
to Closure Compiler Discuss
I am working to make three.js 'closure compiler' compatible, right now i have only 1762 warnings, but initially i had ~4800, so it's  a good progress from my point of view.
But unfortunately i have some difficulties,  what isn't nice i am not able to rewrite the existing code, i can only add closure annotations, so i could use some help.

Let's say i have a class like this one (original source here https://github.com/mrdoob/three.js/blob/dev/src/math/Quaternion.js#L7) :

```
class Quaternion {

constructor( x = 0, y = 0, z = 0, w = 1 ) {

Object.defineProperty( this, 'isQuaternion', { value: true } );
}

...
}
```
Running the resulting code, i always have .isQuaternion undefined, as far as i know it could be workarounded by 

```
Object.defineProperties(this, {
  isQuaternion: {value: true}
});
```

... but i don't want to rewrite code of the existing library.

Maybe i could solve this issue somehow ?

Thanks for help !

Christian Lewis

unread,
Oct 30, 2020, 4:12:21 PM10/30/20
to Closure Compiler Discuss

From the Closure Compiler docs:

Using Object.defineProperties or ES6 getter/setters:
The compiler does not understand these constructs well. ES6 getter and setters are transformed to Object.defineProperties(…) through transpilation. Currently, the compiler is unable to statically analyze this construct and assumes properties access and set are side effect free. This can have dangerous repercussions.

I can reproduce your issue as well, the compiler name-mangles the 'isQuaternion' property name despite it being defined as a string literal. This issue from 2014 seems related.

Confused why three.js would define this.isQuaternion = true with Object.defineProperties(...) in the source? Agreed that the compiler should process this input without issue, but with a quirk like that, I’m not surprised this is an issue.

s...@google.com

unread,
Oct 30, 2020, 5:40:25 PM10/30/20
to Closure Compiler Discuss
The general rule of thumb for Closure Compiler is that quoted and unquoted strings don't mix.  Resolving the #474 might address this issue, but would overall make things harder to reason about.

Is there a reason you can't change it to Object.defineProperties?  The only other alternative would be to add an extern for that property name, so that the compiler recognizes it as something that can't be renamed.  For instance:

/** @externs */
/** @type {?} */
var doNotRename;
doNotRename.isQuaternion;

It's not a great solution, but it should at least prevent the renaming you're concerned with.

Reply all
Reply to author
Forward
0 new messages