1

Google closure compiler complains about this code:

function Message() {
    this.message = "";
    this.nickname = "";
    this.time = 0;
    this.my = false;
};

What is dangerous here? How else it is supposed to create "objects"? For now I do

var m = new Message();

to get an initialized object of "type" Message.

pavelkolodin
  • 2,859
  • 3
  • 31
  • 74

1 Answers1

3

Try annotating the code to tell the compiler that this is a constructor function:

/**
 * A message
 * @constructor
 */
function Message() {
    this.message = "";
    this.nickname = "";
    this.time = 0;
    this.my = false;
};

See https://developers.google.com/closure/compiler/docs/js-for-compiler#overview

Ozrix
  • 3,489
  • 2
  • 17
  • 27
  • Yes, this is an option, but I am interested in roots of the problem. What crime the google closure compiler has detected there? – pavelkolodin Apr 27 '16 at 11:56
  • 1
    the compiler thinks you are referring to the window object, not the instance of Message, because it doesn't know if Message is a constructor or not – Ozrix Apr 27 '16 at 11:57
  • one of the basic features of compilers is type checking, that's why you need to annotate. – Ozrix Apr 27 '16 at 12:03
  • 1
    @pavelkolodin in ES5, there is no way to determine whether a function is a constructor or not until it's used so you have to add a constructor annotation. ES6 classes take care of this. The error comes from `var m = Message() //no new` – Chad Killingsworth Apr 27 '16 at 22:29