Detecting use of properties not initialised in the constructor

16 views
Skip to first unread message

Tom Payne

unread,
Dec 4, 2013, 8:31:59 AM12/4/13
to closure-comp...@googlegroups.com
Hi,

I want my code to work well on V8 which uses hidden classes. For hidden classes to work well, properties have to be initialised in the same order, and the easiest way to achieve this is to initialise them in the constructor. This advice was given by the V8 team in this presentation, starting from slides 26-32:

To help write code that does this, is it possible for the compiler to warn/error if you use a property that is either not defined or not initialised in the constructor, something like:


/**
 * @constructor
 */
MyClass = function() {
  /** @type {number} */
  this.foo = 0; // declared and initialized
  /** @type {number} */
  this.bar; // declared, not initialized
  // this.baz neither declared nor initialized
};


/**
 */
MyClass.prototype.xyzzy = function() {
  this.foo = 1; // happy, assignment to a declared and initialised property
  this.bar = 2; // WARNING: assignment to property 'bar' which is not initialised in constructor
  this.baz = 3; // ERROR: assignment to property 'baz' which is neither initialised nor declared in constructor
};


Cheers,
Tom

Ilia Mirkin

unread,
Dec 4, 2013, 8:59:48 AM12/4/13
to closure-comp...@googlegroups.com
@struct works for the ERROR part, I'm not aware of anything that'll
handle the warning bit.
> --
>
> ---
> You received this message because you are subscribed to the Google Groups
> "Closure Compiler Discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to closure-compiler-d...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

Tom Payne

unread,
Dec 4, 2013, 9:11:07 AM12/4/13
to closure-comp...@googlegroups.com
Awesome, works perfectly, thanks. I prefer errors to warnings anyway :)
Reply all
Reply to author
Forward
0 new messages