1

google-closure-compiler in advanced mode, warns for the following code. This is caused by namespace flattening.

var com.my.test.namespace = {};
com.my.test.namespace.a = new Class ({
    name : "test",
    initialize : function() {   //constructor
        alert(this.name);
    }
});

com.my.test.namespace.a();

When running the google-closure-compiler in ADVANCED mode with debug enabled, com.my.test.namespace.a is replaced to com$my$test$namespace$a

So, the minified code is roughly the following,

var com.my.test.namespace = {};
com$my$test$namespace$a = new Class ({
    name : "test",
    initialize : function() {   //constructor
        alert(this.name);
    }
});

com$my$test$namespace$a();

When, com$my$test$namespace$a() is invoked, "this" isn't com.my.test.namespace anymore, it is the window, and hence the compiler warning.

some documentation suggests to replace "this" with com.my.test.namespace.a to get around this issue. But, is that the right thing to do? what does com.my.test.namespace.a.name point to? It surely does not seem like the current instances "name" property.

What is the right way to do it? com.my.test.namespace.a.prototype.name ?

PS:
I am using mootools library for the Class method.
Sam Hosseini
  • 813
  • 2
  • 9
  • 17
v2b
  • 1,436
  • 9
  • 15
  • you instantiate a class constructor function with new. i.e. `new com$my$test$namespace$a();`, at which point `this` will be your new object instance. – Dimitar Christoff Jul 26 '13 at 23:58

1 Answers1

2

If initialize is the constructor, then the "this" should be name of the type not the namespace. Here is how this should be annotated for the compiler

/** @const */
var namespace = {};

/** @constructor */
namespace.a = new Class (/** @lends {namespace.a.prototype} */{
    name : "test",
    initialize : function() {
        alert(this.name);
    }
});

new namespace.a();

Here is what I have:

  1. a const namespace. Not required but improves type checking.
  2. a constructor declaration (introduces a type name)
  3. @lends on the object literal, indicates that the properties are being used in a type declaration.

@lends is necessary here because the Closure Compiler doesn't have any specific knowledge built in about Moo tools' Class declaration and you need to help it understand that it is being used as part of the type definition.

John
  • 5,443
  • 15
  • 21
  • Is the warning for the use of "this" being dangerous because the closure compiler does not understand that this method is the constructor? – v2b Jul 31 '13 at 20:17
  • Because it doesn't know it is a member of a class at all. – John Aug 01 '13 at 00:35