3

I have some code that looks like this:

var MyObject = function () {
  this.Prop1 = "";
  this.Prop2 = [];
  this.Prop3 = {};
  this.Prop4 = 0;
}

And then I later have this:

var SomeObject = new MyObject();

When I run my code through closure compiler in advanced mode, I'm getting the warning dangerous use of the global this object on every line where I have this.Prop =

What am I doing that's "dangerous" and how should I rewrite my code?

Thanks for your suggestions.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • possible duplicate of this: http://stackoverflow.com/questions/5301373/closure-compiler-warning-dangerous-use-of-the-global-this-object – William Niu Jul 01 '12 at 01:11

2 Answers2

6

I would recommend writing it like this:

function MyObject() {
  this.Prop1 = "";
  this.Prop2 = [];
  this.Prop3 = {};
  this.Prop4 = 0;
}

However, the real fix is to use the @constructor JSDoc notation on the line before the constructor:

/** @constructor */
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • ok, thanks, it was the missing @constructor that was causing the problem. – frenchie Jul 01 '12 at 01:25
  • If this were a function that modified an existing object (rather than a method to be called with "new") you can use the "@this {SomeType}" annotation. – John Jul 02 '12 at 16:49
4

The Closure Compiler Error and Warning Reference provides detailed explanations for the warnings related to the dangerous use of this:

  • JSC_UNSAFE_THIS
  • JSC_USED_GLOBAL_THIS

The warning about using the global this object helps prevent accidentally calling a constructor function without the new keyword, which would result in the constructor properties leaking into the global scope. However, for the compiler to know which functions are intended to be constructors, the annotation /** @constructor */ is required.

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117